2

CTE を使用して SQL Server のツリーをトラバースしようとしています。理想的には、出力として希望するのは、ツリーの各ノードについて、ツリーの上から 2 番目にある対応するノードを示すテーブルです。

特定のノードからツリーをトラバースするための基本的なコードがいくつかありますが、目的の出力を生成するように変更するにはどうすればよいですか?

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 ...

ヒントやポインタをありがとう。

4

1 に答える 1

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

于 2013-09-20T05:51:01.867 に答える