如何计算匹配位于不同行的两个 ID 的总和 - Redshift

How do I make a sum matching two IDs located in different rows - Redshift

id parentid amount
79648627 79648626 1
79648626 null 2

当前 Table,我想将 parentid 与 id 匹配,如果它们匹配,则在 parentid 为 null 的情况下获得相同的金额值,换句话说,期望的结果:

id parentid amount
79648627 79648626 2
79648626 null 2

如果只有一层层次结构,那么您可以使用子查询来获取结果。

 create table testtable(id int,  parentid int,  amount int);
 insert into testtable values(79648627, 79648626,   1);
 insert into testtable values(79648626, null,       2);

查询:

 select id,parentid, 
 (case when parentid is not null then (select amount from testtable tt where tt.id=t.parentid) else amount end )amount
 from testtable t

输出:

id parentid amount
79648627 79648626 2
79648626 null 2

dbhere