Skip to content
Advertisement

Make parent and child hierarchy with records for parents as well as children

I have a parent-child id_table hierarchy – e.g.

I’m building a visual tree hierarchy, where above data would be formatted as:

Now I want to modify this query to include a row for each parent standalone without the child, so above data would become:

To get the first result, I am building the data with repeated left joins (using above first data example) as to my understanding I can’t do this with recursion, e.g.:

This gets me the second example, but I’m lacking a record for each parent as well, as shown in the third example.

I assume this is probably a simple question, I’m just struggling with the syntax. TIA for any help.

EDIT: I had a prior question for a similar implementation in SAS EG: SQL – Recursive Tree Hierarchy with Record at Each Level, however that was with the SAS SQL implementation which is much more restricted – with that method I eventually had to just create temp tables at each level then union the end result, which was messy. Trying to find a cleaner solution.

Advertisement

Answer

GROUP BY ROLLUP can be used to create those extra rows:

Or a Recursive Query to traverse through the hierarchy, built the path and then split it into columns:

Don’t know which one is more efficient.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement