oracle每层节点的求和(父节点是下一层子节点的和,无子节点则为自身)

类似表

ID,ParentID,Amount

1,0,66

2,1,23

3,1,37

4,2,11

5,2,15

想要输出的结果

1,0,66,60

2,1,23,26

3,1,37,37

4,2,11,11

5,2,15,15

章鱼哥48030 发布于 2022-7-24 16:38
1min目标场景问卷 立即参与
回答问题
悬赏:5 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共1回答
最佳回答
0
CD20160914Lv8专家互助
发布于2022-7-24 16:46(编辑于 2022-7-24 17:17)

没有看懂结果是如何得来的。。。

with tmp as (

select 1 as ID, 0 as ParentID, 66 as Amount from dual union all

select 2 as ID, 1 as ParentID, 23 as Amount from dual union all

select 3 as ID, 1 as ParentID, 37 as Amount from dual union all

select 4 as ID, 2 as ParentID, 11 as Amount from dual union all

select 5 as ID, 2 as ParentID, 15 as Amount  from dual

select 

a.id,

a.parentid,

a.amount,

sum(case when b.parentid is null  then a.amount else b.amount end) as 求和

 from tmp a

left join tmp b on a.id=b.parentid

group by a.id,a.parentid,a.amount

image.png

  • 2关注人数
  • 268浏览人数
  • 最后回答于:2022-7-24 17:17
    请选择关闭问题的原因
    确定 取消
    返回顶部