I have a requirement to build a table from a hierarchical table. Table structure as below:
emp_hier table:
| emp_id | supervisorId |
|---|---|
| 100 | null |
| 1 | 100 |
| 2 | 1 |
| 3 | 2 |
New table:
I have to write a select query on the emp_heir table and the selected data should look like this:
| sel_emp_id | rel_emp_id | relation | depth_lvl |
|---|---|---|---|
| 100 | 100 | self | 0 |
| 100 | 1 | My Repotee | -1 |
| 100 | 2 | My Repotee | -2 |
| 100 | 3 | My Repotee | -3 |
| 1 | 100 | My Mgr | 1 |
| 1 | 1 | self | 0 |
| 1 | 2 | My Repotee | -1 |
| 1 | 3 | My Repotee | -2 |
| 2 | 1 | My Mgr | 1 |
| 2 | 2 | self | 0 |
| 2 | 3 | My Repotee | -1 |
| 3 | 100 | My Mgr | 3 |
| 3 | 1 | My Mgr | 2 |
| 3 | 2 | My Mgr | 1 |
| 3 | 3 | self | 0 |
You can use
UNION ALLto combine a hierarchical query to get each row and its children to another hierarchical query to get all the ancestors:Which, for your sample data:
Outputs:
db<>fiddle here