在自引用表SQL Server上找到最高的祖父母

dan*_*ner 1 sql sql-server stored-procedures

我在SQL Server中有此表:

Parent Child 1 2 89 7 2 3 10 5 3 4

我需要构建一个递归存储过程,以找到任何孩子的最大升序。

例如:如果我想找到最大上升数4,它应该返回1,因为:

4是3的孩子。

3是2的孩子。

2是1的子代。

所以我可以找到最终的父母。

Cod*_*ent 5

递归CTE的完美工作:

;WITH
    cte1 AS
    (   -- Recursively build the relationship tree
        SELECT      Parent
                ,   Child
                ,   AscendentLevel = 1
        FROM        my_table
        UNION ALL
        SELECT      t.Parent
                ,   cte1.Child
                ,   AscendentLevel = cte1.AscendentLevel + 1
        FROM        cte1
        INNER JOIN  my_table    t   ON t.Child = cte1.Parent
    ),
    cte2 AS
    (   -- Now find the ultimate parent
        SELECT      Parent
                ,   Child
                ,   rn = ROW_NUMBER() OVER (PARTITION BY Child ORDER BY AscendentLevel DESC)
        FROM        cte1
    )

SELECT  *
FROM    cte2
WHERE   rn = 1
OPTION  (MAXRECURSION 0)
Run Code Online (Sandbox Code Playgroud)