我正在尝试使用 CTE 遍历 SQL Server 中的树。理想情况下,我想要的输出是一个表格,它为树中的每个节点显示从树顶部起第二个对应的节点。
我有一些基本代码可以从给定节点遍历树,但是如何修改它以产生所需的输出?
DECLARE @temp TABLE
(
Id INT
, Name VARCHAR(50)
, Parent INT
)
INSERT @temp
SELECT 1,' Great GrandFather Thomas Bishop', null UNION ALL
SELECT 2,'Grand Mom Elian Thomas Wilson' , 1 UNION ALL
SELECT 3, 'Dad James Wilson',2 UNION ALL
SELECT 4, 'Uncle Michael Wilson', 2 UNION ALL
SELECT 5, 'Aunt Nancy Manor', 2 UNION ALL
SELECT 6, 'Grand Uncle Michael Bishop', 1 UNION ALL
SELECT 7, 'Brother David James Wilson',3 UNION ALL
SELECT 8, 'Sister Michelle Clark', 3 UNION ALL
SELECT 9, 'Brother Robert James Wilson', 3 UNION ALL
SELECT 10, 'Me Steve James Wilson', 3
;WITH cte AS
(
SELECT Id, Name, Parent, 1 as Depth
FROM @temp
WHERE Id = 8
UNION ALL
SELECT t2.*, Depth + 1 as 'Depth'
FROM cte t
JOIN @temp t2 ON t.Parent = t2.Id
)
SELECT *
, MAX(Depth) OVER() - Depth + 1 AS InverseDepth
FROM cte
作为输出,我想要类似的东西
Id Name depth2_id depth2_name
8 Sister Michelle .. 2 Grand Mom Elian ....
7 Brother David .. 2 Grand Mom Elian ....
4 Uncle Michael .. 2 Grand Mom Elian ...
感谢您提供任何提示或指示。