[퀴즈] 계층구조 쿼리의 이해 - 직상위자 이름 가져오기
사원번호, 성명, 상사 사원번호 를 가진 테이블 emp가 있습니다.
이 테이블의 자료를 다음과 같은 계층구조로 표현하세요.
WITH emp AS
(
SELECT 7369 empno, 'SMITH' ename, 7902 mgr FROM dual
UNION ALL SELECT 7499, 'ALLEN' , 7698 FROM dual
UNION ALL SELECT 7521, 'WARD' , 7698 FROM dual
UNION ALL SELECT 7566, 'JONES' , 7839 FROM dual
UNION ALL SELECT 7654, 'MARTIN', 7698 FROM dual
UNION ALL SELECT 7698, 'BLAKE' , 7839 FROM dual
UNION ALL SELECT 7782, 'CLARK' , 7839 FROM dual
UNION ALL SELECT 7788, 'SCOTT' , 7566 FROM dual
UNION ALL SELECT 7839, 'KING' , NULL FROM dual
UNION ALL SELECT 7844, 'TURNER', 7698 FROM dual
UNION ALL SELECT 7876, 'ADAMS' , 7788 FROM dual
UNION ALL SELECT 7900, 'JAMES' , 7698 FROM dual
UNION ALL SELECT 7902, 'FORD' , 7566 FROM dual
UNION ALL SELECT 7934, 'MILLER', 7782 FROM dual
)
SELECT * FROM emp;
[원본]
[결과]
EMPNO
ENAME
MGR
EMPNO
ENAME
MGR
LV
MGR_ENAME
7369
SMITH
7902
7839
KING
1
7499
ALLEN
7698
7566
-JONES
7839
2
KING
7521
WARD
7698
7788
--SCOTT
7566
3
JONES
7566
JONES
7839
7876
---ADAMS
7788
4
SCOTT
7654
MARTIN
7698
7902
--FORD
7566
3
JONES
7698
BLAKE
7839
7369
---SMITH
7902
4
FORD
7782
CLARK
7839
7698
-BLAKE
7839
2
KING
7788
SCOTT
7566
7499
--ALLEN
7698
3
BLAKE
7839
KING
7521
--WARD
7698
3
BLAKE
7844
TURNER
7698
7654
--MARTIN
7698
3
BLAKE
7876
ADAMS
7788
7844
--TURNER
7698
3
BLAKE
7900
JAMES
7698
7900
--JAMES
7698
3
BLAKE
7902
FORD
7566
7782
-CLARK
7839
2
KING
7934
MILLER
7782
7934
--MILLER
7782
3
CLARK
정답은 몇일뒤에 올리겠습니다.
[정답보기] <=== 트리플클릭
SELECT empno
, LPAD('-',LEVEL-1,'-') || ename ename
, mgr
, LEVEL lv
, PRIOR ename mgr_ename
FROM emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
;