如何'ungroup'聚合数据到行?

How to 'ungroup' aggregated data to rows?

我有一个具有类似架构的 table:

basket_id | product | volume
101       | apple   | 3
102       | apple   | 2
102       | orange  | 2

我正在尝试 'ungroup' 或 'deaggregate' table 以下内容。

期望的输出:

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

我尝试了一些联合和案例陈述,但 none 毫不费力地给了我想要的结果。

解决它的方法是生成一个数字列表,然后加入它:

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 子查询。

基本上,您需要一个序列号。如果你的 table 足够大(如你的情况),你可以直接使用它:

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;

如果 table 不够大,您可能会有 table 或更大的数字 table 潜伏。否则,您可以使用 joins.

构建一个