【问题标题】:Postgres with recursive - result to include both grandparent and grandchildren具有递归的 Postgres - 结果包括祖父母和孙子女
【发布时间】:2020-12-09 21:28:02
【问题描述】:

我的家谱包含孩子和父母。我可以编写一个查询,使用 postgres with recursive 返回给定人员的孙辈。但是我怎样才能将祖父母包括在结果中呢?我的目标是报告孙辈的数量,按祖父母 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

【问题讨论】:

  • 请发布表格的外观以及您对输出的确切期望。
  • 嗨@Nik - 更新后的问题能回答你的问题吗?

标签: postgresql recursive-query with-statement


【解决方案1】:

这样就可以了:

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;

【讨论】: