使用 CTE 确定家庭成员的特定层次结构 ID

Using CTE to determine a specific Hierarchical ID for Family Members

我正在尝试弄清楚如何在使用 CTE 时将递增 ID 附加到我的结果集。

我的 table 有这样的数据:

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,但我们将不胜感激在正确方向上提供的任何帮助或产品!

这听起来很简单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;

Here 是一个 db<>fiddle.