I am trying to create a query that shows the different levels of the hierarchy in different columns For now it looks like this
| Parent | Child |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 5 |
I want the output to look like this
| Root | Child1 | Child2 | Child3 | Child4 |
|---|---|---|---|---|
| 1 | 2 | 4 | ||
| 1 | 2 | 5 | ||
| 1 | 3 | 5 |
I am trying to create a query that shows the different levels of the hierarchy in different columns For now it looks like this
| Parent | Child |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 5 |
I want the output to look like this
| Root | Child1 | Child2 | Child3 | Child4 |
|---|---|---|---|---|
| 1 | 2 | 4 | ||
| 1 | 2 | 5 | ||
| 1 | 3 | 5 |
On
A simple self-join does the job:
select
c1.parent as root,
c1.child as child1,
c2.child as child2,
c3.child as child3,
c4.child as child4
from mytable c1
left join mytable c2 on c2.parent = c1.child
left join mytable c3 on c3.parent = c2.child
left join mytable c4 on c4.parent = c3.child
where c1.parent not in (select child from mytable)
order by root, child1, child2, child3, child4;
Demo: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=fcc7963188b28b519417142a4b5f70f6
You can use a recursive query:
or:
Which, for the sample data:
Both output:
db<>fiddle here