在SQL中将一行拆分为多行,并将金额平均分配

时间:2020-03-20 10:59:36

标签: sql amazon-redshift

我有一个包含ID,金额列和计数列的表。我想根据count列将它们分为多行。然后,我希望将数量列在这些行之间平均分配,并根据原始ID和行数创建一个新ID。 表格的外观如下:

ID      Amount   Count
1001    8        2
1002    15       3

这是所需的输出

ID      Amount
1001-1  4
1001-2  4
1002-1  5
1002-2  5
1002-3  5

什么是最好的方法?

2 个答案:

答案 0 :(得分:0)

您可以使用递归CTE。看起来像这样:

with recursive cte as (
      select id, amount / cnt as amount, cnt, 1 as lev 
      from t
      union all
      select id, amount, cnt, lev + 1
      from t
      where lev < cnt
     )
select id || '-' || lev, amount
from cte;

请注意,这使用标准语法;确切的语法可能会因数据库而异。

答案 1 :(得分:0)

不幸的是,Redshift不支持递归查询。

这是使用临时数字表的另一种选择。

create temp table tmp(n int);
insert into tmp(n) values (1), (2), (3), (4), ...; -- expand as needed

select concat(t.id, '-', p.n) id, t.amount/t.count amount
from mytable t
inner join tmp p on p.n <= t.count
order by t.id, p.n