Postgresql 带递归的博士后-结果包括祖父母和孙辈

Postgresql 带递归的博士后-结果包括祖父母和孙辈,postgresql,recursive-query,with-statement,Postgresql,Recursive Query,With Statement,我的家谱包括孩子和父母。我可以编写一个查询,使用带递归的postgres返回给定人员的孙子。但是我怎么能把祖父母也包括在结果中呢?我的目标是报告按祖父母id分组的孙辈数量。如何在最终结果中引用查询的非递归部分 已编辑-示例表: child parent 11 null 12 null 13 null 21 11 22 11 31 12 32 12 33 12 41 13 81 21 82 21

我的家谱包括孩子和父母。我可以编写一个查询,使用带递归的postgres返回给定人员的孙子。但是我怎么能把祖父母也包括在结果中呢?我的目标是报告按祖父母id分组的孙辈数量。如何在最终结果中引用查询的非递归部分

已编辑-示例表:

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
这将有助于:

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;

请发布表格的外观以及您对输出的具体期望。hi@Nik-更新后的问题是否回答了您的问题?文档说明了它是如何工作的。