树结构数据怎么按照父格向下汇总

数据库表有三列,分别是p_dept_id,dept_id,num,怎么才能按照p_dept_id汇总下级所有数据。

p_dept_iddept_idnum
AAA2AAA5
AAB3AAB3
数据AAC4展示结果AAC4
AAAAA1
AAAAB1
AAAAC1

image.png

FineReport Basis 发布于 2023-3-11 08:47 (编辑于 2023-3-11 08:48)
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共2回答
最佳回答
0
CD20160914Lv8专家互助
发布于2023-3-11 09:50

oralce里面类似这样,你也没有说明白关联逻辑,我只是按你模拟的把结果弄出来了。其它的数据库也可以用,只是mysql低于8的版本不能用with这种语法

with tmp as (

select 'A' as p_dept_id,'AA' as dept_id,2 as num from dual union all

select 'A' as p_dept_id,'AB' as AA,3 as num from dual union all

select 'A' as p_dept_id,'AC' as AB,4 as num from dual union all

select 'AA' as p_dept_id,'AAA' as AC,1 as num from dual union all

select 'AA' as p_dept_id,'AAB' as AAA,1 as num from dual union all

select 'AA' as p_dept_id,'AAC' as AAB,1 as num from dual

)

select t.p_dept_id,t.dept_id,sum(t.my_num) as my_num from (

 select 

   a.p_dept_id,

   a.dept_id,

   b.num as my_num

   from tmp a

join tmp b on a.dept_id=b.p_dept_id

where length(a.p_dept_id)=1

union all

 select 

   a.p_dept_id,

   a.dept_id,

   a.num as my_um

   from tmp a

where length(a.p_dept_id)=1

) t

group by t.p_dept_id,t.dept_id

image.png

最佳回答
0
用户k6280494Lv6资深互助
发布于2023-3-11 09:00

把num列的左父格设置为ID列,num列汇总求和

  • 3关注人数
  • 312浏览人数
  • 最后回答于:2023-3-11 09:50
    请选择关闭问题的原因
    确定 取消
    返回顶部