Code:
Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production
JServer Release 8.1.7.4.0 - Production
SQL> CREATE TABLE tree (
2 node_id NUMBER, node_name VARCHAR2 (30),
3 node_level NUMBER, parent_node_id NUMBER);
Table created.
SQL>
SQL> INSERT INTO tree VALUES (1023, 'node_district_a', 4, 1022);
1 row created.
SQL> INSERT INTO tree VALUES (1022, 'node_region_a', 3, 1021);
1 row created.
SQL> INSERT INTO tree VALUES (1021, 'node_state_a', 2, 1020);
1 row created.
SQL> INSERT INTO tree VALUES (1020, 'node_company_a', 1, 0);
1 row created.
SQL> INSERT INTO tree VALUES (1080, 'node_district_b', 4, 1079);
1 row created.
SQL> INSERT INTO tree VALUES (1079, 'node_region_b', 3, 1078);
1 row created.
SQL> INSERT INTO tree VALUES (1078, 'node_state_b', 2, 1077);
1 row created.
SQL> INSERT INTO tree VALUES (1077, 'node_company_b', 1, 0);
1 row created.
SQL> SELECT MAX (company) company, MAX (state) state,
2 MAX (region) region, MAX (district) district
3 FROM (SELECT b.*, SUM (DECODE (lvl, lag_lvl + 1, 0, 1))
4 OVER (ORDER BY row_num) grp
5 FROM (SELECT DECODE (node_level, 1, node_name) company,
6 DECODE (node_level, 2, node_name) state,
7 DECODE (node_level, 3, node_name) region,
8 DECODE (node_level, 4, node_name) district,
9 row_num, lvl, LAG (lvl) OVER (ORDER BY row_num) lag_lvl
10 FROM (SELECT node_id, node_name, node_level,
11 parent_node_id, ROWNUM row_num, LEVEL lvl
12 FROM tree
13 START WITH node_id IN (1023, 1080)
14 CONNECT BY PRIOR parent_node_id = node_id)) b)
15 GROUP BY grp;
COMPANY STATE REGION DISTRICT
--------------- --------------- --------------- ---------------
node_company_a node_state_a node_region_a node_district_a
node_company_b node_state_b node_region_b node_district_b
SQL> SELECT path
2 FROM (SELECT path, LEAD (path) OVER (
3 ORDER BY ROWNUM) next_path
4 FROM (SELECT ROWNUM row_num,
5 hierarchy.branch (
6 LEVEL, node_name, ', ') path
7 FROM tree
8 START WITH node_id IN (1023, 1080)
9 CONNECT BY PRIOR parent_node_id = node_id))
10 WHERE next_path NOT LIKE path || '%' OR next_path IS NULL;
PATH
----------------------------------------------------------------------------------------------------
node_district_a, node_region_a, node_state_a, node_company_a
node_district_b, node_region_b, node_state_b, node_company_b
SQL>