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
source
share