sql server - SQL Query / Herigate data join -
i have 2 tables, first person data
id name
the second has each person relatives
primary key field person (references person.id) relativetype (mother or father) parent (references person.id)
i'm trying sons , grandsons of specific person , i'm stuck integrating grandsons in query results. i'm using sql server.
any ideas?
the query need depends highly of how many level have of parent-child relationship. if can change schema, recommend turn using hierarchyid
sql server specific data type. have here.
in following, assume have 2 levels. father - son - grandson
;with sons ( select pdf.id, pdf.name, pdd.id parentid, pdd.name parent persondata pdf join personrelative pr on pdf.id = pr.parent join persondata pdd on pr.person = pdd.id //selecting parents ) select pd.name, s.name son, 'son' type persondata pd join sons s on pd.id = s.parentid union select pd.name, gs.name son, 'grandson' type persondata pd join sons s on pd.id = s.parentid join sons gs on s.id = gs.parentid
Comments
Post a Comment