Finding Top Level Parent ID

前端 未结 3 1577
挽巷
挽巷 2021-01-28 10:10

In one table I have two columns like below

ID  ParentID
1   0x0
2   1
3   2
9   0x0
5   9
6   5
25  0x0
30  25

How to get top level parent ID

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 10:25

    You can use a recursive CTE:

    WITH CTE AS
    (
        SELECT *, 1 [Level]
        FROM dbo.YourTable
        UNION ALL
        SELECT A.ID, B.[Parent ID], [Level] + 1
        FROM CTE A
        INNER JOIN dbo.YourTable B
            ON A.[Parent ID] = B.Id
    ), CTE2 AS
    (
        SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY [Level] DESC)
        FROM CTE
        WHERE [Parent ID] <> 0
    )
    SELECT ID, [Parent ID] [Top Level Parent Id]
    FROM CTE2
    WHERE RN = 1
    OPTION (MAXRECURSION 0)
    ;
    

    Here is a link with a demo.

    The results are:

    ╔════╦═════════════════════╗
    ║ ID ║ Top Level Parent Id ║
    ╠════╬═════════════════════╣
    ║  2 ║                   1 ║
    ║  3 ║                   1 ║
    ║  5 ║                   9 ║
    ║  6 ║                   9 ║
    ║ 30 ║                  25 ║
    ╚════╩═════════════════════╝
    

提交回复
热议问题