I have a table that has child_id and parent_id. The child_id has the leaf node and the parent_id has the immediate parent. I need to get all the parents and all their children using a SQL query
Could someone help me with this?
I tried a recursive CTE to get all the children of a particular parent and I have a query for this, but now I need to get all the parents and all their children in a table.
WITH CTE as (
SELECT child_id,parent_id
FROM Hierarchy
where parent_id ='Africa'
UNION ALL
SELECT Hierarchy.child_id,Hierarchy.parent_id
FROM Hierarchy
inner join CTE on Hierarchy.parent_id=cte.child_id
where Hierarchy.parent_id !='Africa'
)
SELECT *
FROM CTE
OPTION (MAXRECURSION 0)
With the above query, I just get Africa's children. I want all the children of all the continents