WITH T AS ( SELECT '1' ID , '0' UP_ID FROM DUAL UNION ALL SELECT '2' ID , '1' UP_ID FROM DUAL UNION ALL SELECT '3' ID , '2' UP_ID FROM DUAL UNION ALL SELECT 'A' ID , '0' UP_ID FROM DUAL UNION ALL SELECT 'B' ID , 'A' UP_ID FROM DUAL UNION ALL SELECT 'C' ID , 'B' UP_ID FROM DUAL ) SELECT MAX(CASE WHEN LV = 1 THEN ID END) AS LV1 , MAX(CASE WHEN LV = 2 THEN ID END) AS LV2 , MAX(CASE WHEN LV = 3 THEN ID END) AS LV3 FROM ( SELECT T.* , LEVEL LV , CONNECT_BY_ROOT(ID) GRP FROM T START WITH UP_ID = '0' CONNECT BY PRIOR ID = UP_ID ) GROUP BY GRP
-- PIVOT 이용 WITH T AS ( SELECT '1' ID , '0' UP_ID FROM DUAL UNION ALL SELECT '2' ID , '1' UP_ID FROM DUAL UNION ALL SELECT '3' ID , '2' UP_ID FROM DUAL UNION ALL SELECT 'A' ID , '0' UP_ID FROM DUAL UNION ALL SELECT 'B' ID , 'A' UP_ID FROM DUAL UNION ALL SELECT 'C' ID , 'B' UP_ID FROM DUAL ) SELECT * FROM ( SELECT T.ID , LEVEL LV , CONNECT_BY_ROOT(ID) GRP FROM T START WITH UP_ID = '0' CONNECT BY PRIOR ID = UP_ID ) PIVOT ( MIN(ID) FOR LV IN ( 1 LV1 , 2 LV2, 3 LV3) )
SELECT REGEXP_SUBSTR(p, '[^,]+', 1, 1) lv1 , REGEXP_SUBSTR(p, '[^,]+', 1, 2) lv2 , REGEXP_SUBSTR(p, '[^,]+', 1, 3) lv3 , REGEXP_SUBSTR(p, '[^,]+', 1, 4) lv4 FROM (SELECT SYS_CONNECT_BY_PATH(empno, ',') p FROM emp --WHERE CONNECT_BY_ISLEAF = 1 -- 최하위 노드만 출력 START WITH mgr IS NULL CONNECT BY PRIOR empno = mgr -- AND LEVEL <= 3 -- 3 레벨 까지만 출력 ) ;