5

假设我有以下树:

CREATE TABLE Tree(Id int, ParentId int, Name varchar(20), Level int)

INSERT INTO Tree(Id, ParentId, Name, Level)
SELECT 1, NULL, 'Bob', 0 UNION ALL 
SELECT 2, 1, 'John', 1 UNION ALL
SELECT 3, 1, 'Bill', 1 UNION ALL
SELECT 4, 3, 'Peter', 2 UNION ALL
SELECT 5, 4, 'Sarah', 3

我需要一个脚本来在特定级别找到给定节点的祖先:

例如,Sarah 在级别 2 的祖先是 Peter,而 Peter 在级别 0 的祖先是 Bob。

有没有一种简单的方法可以使用分层 CTE 来做到这一点?sqlfiddle

4

3 回答 3

4

你可以这样做:

;WITH TreeCTE
AS
(
    SELECT Id, ParentId, Name, Level
    FROM Tree
    WHERE Id = 5
    UNION ALL 
    SELECT t.Id, t.ParentId, t.Name, t.Level
    FROM TreeCTE AS c
    INNER JOIN Tree t ON c.ParentId = t.Id  
)
SELECT * FROM TreeCTE;

这将为您提供父子链,从Sarah以.id = 5parentid = NULL

这是更新的sql小提琴

于 2012-09-25T11:24:03.373 回答
3
declare @fromid int, @level int
select @fromid = 5, @level = 2 -- for sarah's ancestor at level 2
select @fromid = 4, @level = 0 -- for peter's ancestor at level 0

;with cte as (    
    select * from tree where id = @fromId
    union all
    select t.Id, t.ParentId, t.Name, t.Level from cte
        inner join tree t on t.id = cte.ParentId
) 
    select * from cte
    where Level=@level
于 2012-09-25T11:24:16.260 回答
0

试试这个:

DEclare @level int=0
Declare @name varchar(10)='Peter'
;WITH CTE as (
select * from tree where Name=@name
UNION ALL
select t.* from Tree t inner join CTE c on
t.ID=c.ParentId and t.Level >=@level)
select top 1 Name as Ancestor from CTE order by id
于 2012-09-25T11:34:39.433 回答