具有递归的 Postgres - 结果包括祖父母和孙子女
Postgres with recursive - result to include both grandparent and grandchildren
我的家谱包含 children 和 parents。我可以使用 postgres with recursive
为给定的人编写一个 returns grandchildren 的查询。但是我怎样才能在结果中包括祖父母呢?我的目标是报告祖父母 id 分组的祖父 children 的数量。如何在最终结果中引用查询的 non-recursive 部分?
已编辑 - 示例 table:
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
non-recursive 部分查询:
select distinct child where parent is null -- as grandparent
期望的结果:
grandparent, grandchildren
11 3
12 2
13 0
这样做:
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;
我的家谱包含 children 和 parents。我可以使用 postgres with recursive
为给定的人编写一个 returns grandchildren 的查询。但是我怎样才能在结果中包括祖父母呢?我的目标是报告祖父母 id 分组的祖父 children 的数量。如何在最终结果中引用查询的 non-recursive 部分?
已编辑 - 示例 table:
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
non-recursive 部分查询:
select distinct child where parent is null -- as grandparent
期望的结果:
grandparent, grandchildren
11 3
12 2
13 0
这样做:
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;