Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

get ancestor based on a condition

$
0
0

hi all,

please see thre sample data below. i am trying to figure out how to get the next available ancestor for a given child.

to get sarah's parent, I need to go to sarah's immidieate parent who is peter, but since the flag is set to 0 for peter, I need to go to peter's parent who is bill - since the falg is set to 1 for bill, sarah's parent would be bill.

bill's parent would be bob as the flag for bob is set to 1

any idea how to do this? thanks in advance for helping out.

DECLARE @Tree TABLE(Id int, ParentId int, Name varchar(20), Flag BIT)

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

SELECT * FROM @Tree


Viewing all articles
Browse latest Browse all 23857

Trending Articles