Multiple Self Join w/Dynamic Level Hierarchy
I'm trying to wrap my head around these multiple self joins with my "Areas" table. The table is structured as so:
Table Name: Areas
----------------------------------------------------
| ID | Area | Parent | Order |
----------------------------------------------------
| 1 | Executive | 0 | 1 |
| 2 | Finance | 1 | 1 |
| 3 | Security | 1 | 3 |
| 4 | Records Management | 1 | 2 |
| 5 | Financial Operations | 2 | 1 |
| 6 | Financial Policy | 2 | 2 |
| 7 | Team A | 5 | 1 |
| 8 | Team B | 5 | 2 |
----------------------------------------------------
Here the hierarchy has 4 levels, but that could change at any time if another area was added to "Team B". Is there a way to query this table to bring back a column for each level in the hierarchy, with the master parent beginning on the left and the last child on the far right. Something like this:
--------------------------------------------------------------------------
| Col 1 | Col 2 | Col 3 | Col 4 |
--------------------------------------------------------------------------
| Executive | NULL | NULL | NULL |
| Executive | Finance | NULL | NULL |
| Executive | Finance | Financial Operations | NULL |
| Executive | Finance | Financial Operations | Team A |
| Executive | Finance | Financial Operations | Team B |
| Executive | Records Management | NULL | NULL |
| Executive | Security | NULL | NULL |
--------------------------------------------------------------------------
Is this possible? Or would you need to know the depth of the hierarchy to write out each join?
Also what would be the most effective way to query this with joins?
|