我有一个具有类似模式的表:
basket_id | product | volume
101 | apple | 3
102 | apple | 2
102 | orange | 2
我正在尝试将表"取消分组"或"取消聚合"为以下内容。
期望输出:
basket_id | product | volume
101 | apple | 1
101 | apple | 1
101 | apple | 1
102 | apple | 1
102 | apple | 1
102 | orange | 1
102 | orange | 1
我尝试过一些工会和案例陈述,但没有一个能毫不费力地给我带来想要的结果。
基本上,您需要一个序列号。如果你的桌子足够大(就像你的情况一样(,你可以直接使用它:
with n as (
select row_number() over (order by basket_id) as n
from t
) t
select t.basket_id, t.product, 1 as volume
from t join
n
on n.n <= t.volume;
如果表不够大,您可能会有一个数字表或更大的表潜伏在周围。否则,您可以使用join
s构建一个
解决问题的方法是生成一个数字列表,然后加入它:
select basket_id, product, 1
from mytable t
inner join (
select 1 n union all select 2 union all select 3
) x on t.volume <= x.n
您可以根据需要使用更多数字展开unioned
子查询。