sql—使用cte确定家庭成员的特定层次id

fhity93d  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(290)

我正在尝试找出如何在使用cte时将递增的id附加到我的结果集。
我的表有如下数据:

PersonId   ParentLinkId   Relation  Name
   1          NULL           F       John Doe
   2           1             S       Jane Doe
   3           1             C       Jack Doe
   4           1             C       Jill Doe

我想添加一个名为relationid的列。基本上,“f”人总是得到“1”,关系“s”总是得到“2”,任何后续的“c”关系都会得到3、4、5……等等
它们由parentlinkid链接,因此parentlinkid=personid。
我试图使用cte递归地增加这个值,但是我一直被困在一个无限循环中
我试过:

WITH FinalData( ParentId, ParentLinkId, Name, Relationship, RelationshipId) AS 
(
    SELECT  ParentId
           ,ParentLinkId
           ,Name
           ,Relationship
           ,1
    FROM FamTable
    WHERE ParentLinkId IS NULL
    UNION ALL
    SELECT FT.ParentId
          ,ParentLinkId
          ,Name
          ,Relationship
          ,RelationshipId + 1
    FROM FamTable FT
    INNER JOIN FinalData ON FT.ParentLinkId = FinalData.ParentId
)
SELECT * FROM 
FinalData

这是我不断得到的结果:

PersonId   ParentLinkId   Relation     Name     RelationshipId
   1           NULL          F       John Doe         1
   2            1            S       Jane Doe         2
   3            1            C       Jack Doe         2
   4            1            C       Jill Doe         2

应该是的

PersonId   ParentLinkId   Relation     Name     RelationshipId
   1           NULL          F       John Doe         1
   2            1            S       Jane Doe         2
   3            1            C       Jack Doe         3
   4            1            C       Jill Doe         4

我想我正在接近使用cte,但任何帮助或在正确的方向将不胜感激!

bmp9r5qi

bmp9r5qi1#

这听起来很简单 row_number() :

select f.*,
       row_number() over (partition by coalesce(ParentLinkId, PersonId)
                          order by (case when relation = 'F' then 1
                                         when relation = 'S' then 2
                                         when relation = 'C' then 3
                                    end), PersonId
                         ) as relationId                                         
from famtable f;

这是一把小提琴。

相关问题