我正在尝试使用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 ...
感谢您的任何提示或指示。
答案 0 :(得分:1)
有点难以得到你的目标,但你可以使用这样的smth:
;with cte AS
(
select
t.Id, t.Name, t.Parent, 1 as Depth,
null as Depth2Parent
from @temp as t
where t.Parent is null
union all
select
t.Id, t.Name, t.Parent, c.Depth + 1 as 'Depth',
isnull(c.Depth2Parent, case when c.Depth = 1 then t.Id end) as Depth2Parent
from cte as c
inner join @temp as t on t.Parent = c.Id
)
select *
from cte
<强> sql fiddle demo 强>