我的家谱里有孩子和父母。我可以使用postgres with recursive编写一个查询,返回给定人的孙辈。但我怎么能把祖父母也包括在结果里呢?我的目标是报告孙辈的数量,按祖父母身份分类。如何在最终结果中引用查询的非递归部分?
编辑-示例表:
child parent
11 null
12 null
13 null
21 11
22 11
31 12
32 12
33 12
41 13
81 21
82 21
83 21
91 33
92 33查询的非递归部分:
select distinct child where parent is null -- as grandparent预期结果:
grandparent, grandchildren
11 3
12 2
13 0发布于 2020-08-20 17:10:46
这样做可以:
with recursive zzz AS (
select child AS grandparent, child AS current_child, 1 AS grand_level
FROM thetable AS tt
where parent is null
UNION
SELECT grandparent, tt.child, grand_level+1
FROM thetable AS tt
JOIN zzz
ON tt.parent = zzz.current_child
)
SELECT grandparent, COUNT(DISTINCT current_child)FILTER(WHERE grand_level = 3) AS grandchildren
FROM zzz
GROUP BY grandparent;https://stackoverflow.com/questions/63506838
复制相似问题