WITH TBL AS (
SELECT '1' C_ID, NULL R_ID FROM DUAL UNION ALL
SELECT '11' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '111' C_ID, '11' R_ID FROM DUAL UNION ALL
SELECT '112' C_ID, '11' R_ID FROM DUAL UNION ALL
SELECT '12' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '121' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '122' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '123' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '13' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '2' C_ID, NULL R_ID FROM DUAL UNION ALL
SELECT '21' C_ID, '2' R_ID FROM DUAL UNION ALL
SELECT '211' C_ID, '21' R_ID FROM DUAL UNION ALL
SELECT '22' C_ID, '2' R_ID FROM DUAL UNION ALL
SELECT '221' C_ID, '22' R_ID FROM DUAL UNION ALL
SELECT '222' C_ID, '22' R_ID FROM DUAL
)
-- 정전개
SELECT LEVEL
,C_ID
FROM TBL
START WITH R_ID IS NULL
CONNECT BY R_ID = PRIOR C_ID
ORDER SIBLINGS BY C_ID
-- 역전개
SELECT LEVEL
,C_ID
FROM TBL T
START WITH NOT EXISTS (SELECT 1 FROM TBL WHERE R_ID = T.C_ID)
CONNECT BY PRIOR R_ID = C_ID
ORDER SIBLINGS BY C_ID
WITH TBL AS (
SELECT '1' C_ID, NULL R_ID FROM DUAL UNION ALL
SELECT '11' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '111' C_ID, '11' R_ID FROM DUAL UNION ALL
SELECT '112' C_ID, '11' R_ID FROM DUAL UNION ALL
SELECT '12' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '121' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '122' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '123' C_ID, '12' R_ID FROM DUAL UNION ALL
SELECT '13' C_ID, '1' R_ID FROM DUAL UNION ALL
SELECT '2' C_ID, NULL R_ID FROM DUAL UNION ALL
SELECT '21' C_ID, '2' R_ID FROM DUAL UNION ALL
SELECT '211' C_ID, '21' R_ID FROM DUAL UNION ALL
SELECT '22' C_ID, '2' R_ID FROM DUAL UNION ALL
SELECT '221' C_ID, '22' R_ID FROM DUAL UNION ALL
SELECT '222' C_ID, '22' R_ID FROM DUAL
)
-- 상방
SELECT 1 LVL
,T1.C_ID
,T1.C_ID CONN_ID
FROM TBL T1
WHERE NOT EXISTS (SELECT 1 FROM TBL WHERE R_ID = T1.C_ID)
UNION ALL
SELECT 2 LVL
,T2.C_ID
,T1.C_ID || '/' ||
T2.C_ID CONN_ID
FROM TBL T1
,TBL T2
WHERE NOT EXISTS (SELECT 1 FROM TBL WHERE R_ID = T1.C_ID)
AND T2.C_ID = T1.R_ID
UNION ALL
SELECT 3 LVL
,T3.C_ID
,T1.C_ID || '/' ||
T2.C_ID || '/' ||
T3.C_ID CONN_ID
FROM TBL T1
,TBL T2
,TBL T3
WHERE NOT EXISTS (SELECT 1 FROM TBL WHERE R_ID = T1.C_ID)
AND T2.C_ID = T1.R_ID
AND T3.C_ID = T2.R_ID
UNION ALL
SELECT 4 LVL
,T4.C_ID
,T1.C_ID || '/' ||
T2.C_ID || '/' ||
T3.C_ID || '/' ||
T4.C_ID CONN_ID
FROM TBL T1
,TBL T2
,TBL T3
,TBL T4
WHERE NOT EXISTS (SELECT 1 FROM TBL WHERE R_ID = T1.C_ID)
AND T2.C_ID = T1.R_ID
AND T3.C_ID = T2.R_ID
AND T4.C_ID = T3.R_ID
ORDER BY CONN_ID