如何一次取回所有祖父母

2022-03-13 00:00:00 sql foreign-keys inner-join sqlite

我在sqlite3(家庭债券)中有两个简单的表:

";Person&Quot;(id,fname,lname)
关系&Quot;(父项/子项)

我想让每个孙子孙女和他们所有的祖父母一起(根据孙子孙女的不同,从1个到4个),这样1行结果=

Distinct Grand child, Grand parent 1, Grand parent 2, Grand parent 3, Grand parent 4

多亏了Caius Jard,我才能让每一个孩子和它的祖父母都被问到另一个星空溢出的问题。但是,到目前为止,我有:
1行=孙子辈,1个祖父母(因此最多需要4行才能获得子代的所有祖父母)。

SELECT c.fname, c.lname, gp.fname, gp.lname  
FROM relations p_c
INNER JOIN relationships gp_p ON gp_p.child = p_c.parent 
INNER JOIN persons gp ON gp.id = gp_p.parent 
INNER JOIN persons c ON c.id = p_c.child
ORDER BY c.id;

如何编辑此内容才能将每个孙子孙女与所有祖父母一起放在单行结果中?

如果可能,请仅使用SELECT(+COUNT/DISTINCT)、WHERE(+IN/EXISTS)、INTER/LEFT JOIN、GROUP BY(+HAVING)、ORDER BY。


解决方案

假设有四个祖父母,您可以枚举并聚合他们:

SELECT fname, lname,
       MAX(CASE WHEN seqnum = 1 THEN grandparent_name END) as grandparent_1,
       MAX(CASE WHEN seqnum = 2 THEN grandparent_name END) as grandparent_2,
       MAX(CASE WHEN seqnum = 3 THEN grandparent_name END) as grandparent_3,
       MAX(CASE WHEN seqnum = 4 THEN grandparent_name END) as grandparent_4
FROM (SELECT c.id, c.fname, c.lname,
             gp.fname || ' ' || gp.lname as grandparent_name,
             ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY gp.fname, gp.lanme) as seqnum 
      FROM relations p_c JOIN
           relationships gp_p
           ON gp_p.child = p_c.parent JOIN
           persons gp
           ON gp.id = gp_p.parent 
           persons c
           ON c.id = p_c.child
     ) cgp
GROUP BY fname, lname, id;

相关文章