Supose the families bellow:
The Build Schema of this is:
create table PersonConn (child int, parent int)
insert into PersonConn values (1,2)
insert into PersonConn values (1,3)
insert into PersonConn values (5,3)
insert into PersonConn values (5,4)
insert into PersonConn values (6,7)
insert into PersonConn values (6,8)
insert into PersonConn values (2,9)
insert into PersonConn values (2,10)
insert into PersonConn values (3,11)
insert into PersonConn values (3,12)
To get the ancestors of a family member I can use recursion as showed bellow:
WITH Childs AS (
SELECT distinct Child, Parent
FROM PersonConn
WHERE Child = 1
UNION ALL
SELECT t2.Child, t2.Parent
FROM [Childs] t1
INNER JOIN PersonConn t2
ON t2.Child = t1.parent
)
SELECT PARENT FROM CHILDS
It will take all the ancestors of selected member (ID 1 in this example), but not the brothers for example. The query goes up only in family tree.
My question is:
How to get all members of a family (sons, parents, grandfathers, uncles, cousins, etc...) starting from a single person?
UPDATE
One method to solve this is a loop that inserts a person in a temporary table. After you could join PersonConn
table with this temporary table and inserts other people. Do this until no one is inserted anymore. I am looking for a more efficient (and elegant) way. I have about 200MM records in PersonConn
table.