SQL tree finds anscestors at a certain level

Let's say I have the following tree:

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

I need a script to find the ancestor of a given node at a certain level:

For example, the ancestor of Sarah at level 2 is Peter, and the ancestor of Peter at level 0 is Bob.

Is there an easy way to do this with a hierarchical CTE? sqlfiddle

+5
source share
3 answers

You can do it:

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

This will give you a parent-child chain starting with Sarah, with id = 5, ending with the top most of the parent elements with parentid = NULL.

Here is the updated sql script

+4
source
declare @fromid int, @level int
select @fromid = 5, @level = 2 -- for sarah ancestor at level 2
select @fromid = 4, @level = 0 -- for peter 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
+3
source

:

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
0

All Articles