gpt4 book ai didi

sql - Postgresql查询获取树的总和

转载 作者:行者123 更新时间:2023-11-29 12:56:50 24 4
gpt4 key购买 nike

大家好,我想问一下关于 postgresql 的问题,以及当您的元素表具有更多级别的后代时,什么是获取列总和的最佳查询。

id id_parent
1 null 3
2 null 4
3 1 2
4 2 3
5 3 4
6 3 2
7 4 5
8 4 7

所以结果将是具有所有树的总和的行,如下所示

id 5 和 6 的值加起来是 6 加上它们的父项的值是 8 加上他的父项是 11,id 为 7 和 8 的项目也是如此,所以 id=2 的祖 parent 的值是 19

id id_parent
1 null 11
2 null 19

提前致谢

最佳答案

使用递归 CTE:

with recursive cte as (
select t.id, t.value, ultimate_parent as id
from t
where id_parent is null
union all
select t.id, t.value, cte.ultimate_parent
from cte join
t
on t.id_parent = cte.id
)
select ultimate_parent, sum(value)
from cte
group by ultimate_parent;

递归部分从最终父级开始——父级为NULL 的记录。然后它会逐步引入较低级别,并保持最终父级的 ID。

最终聚合只是将值加在一起。

关于sql - Postgresql查询获取树的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com