【问题标题】:Split one row into multiple rows in SQL with amounts divided equally在 SQL 中将一行拆分为多行,金额均分
【发布时间】:2020-03-20 10:59:36
【问题描述】:

我有一个包含 ID、金额列和计数列的表。对于每一行,我想根据计数列将它们分成多行。然后我希望金额列在这些行之间平均分配,并根据原始 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

最好的方法是什么?

【问题讨论】:

  • 标记您正在使用的 DBMS(MySQLSQL Server 等......)。

标签: sql amazon-redshift


【解决方案1】:

您可以使用递归 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;

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

【讨论】:

    【解决方案2】:

    很遗憾,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
    

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      相关资源
      最近更新 更多