首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有递归结果的Postgres包括祖父母和孙辈。

问具有递归结果的Postgres包括祖父母和孙辈。
EN

Stack Overflow用户
提问于 2020-08-20 14:04:07
回答 1查看 300关注 0票数 0

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

编辑-示例表:

代码语言:javascript
复制
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

查询的非递归部分:

代码语言:javascript
复制
select distinct child where parent is null -- as grandparent

预期结果:

代码语言:javascript
复制
grandparent, grandchildren
     11           3
     12           2
     13           0
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-20 17:10:46

这样做可以:

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63506838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档