【问题标题】:Find the highest grandparent on self-referencing table SQL Server查找自引用表 SQL Server 上的最高祖父母
【发布时间】:2015-11-03 19:03:05
【问题描述】:

我在 SQL Server 中有这张表:

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

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

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

4 是 3 的孩子。

3 是 2 的孩子。

2 是 1 的孩子。

这样我才能找到最终的父母。

【问题讨论】:

  • 5 的回报是什么? 10 还是 89?
  • 请参考recursive self sql server join..它可能对你有帮助..[Recursive Self Join][1] [1]: stackoverflow.com/questions/1757260/…
  • 任何。我应该编辑它。

标签: sql sql-server stored-procedures


【解决方案1】:

递归 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)

【讨论】:

  • +1 以获得出色的答案。我正在努力总结我的答案,但我看到了你的回复并发现它更好。如果您想将它添加到您的答案中,这是一个 SQL Fiddle。 sqlfiddle.com/#!3/3bf43/1/0
  • 谢谢 Zoff Dino。很好的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多