Consider the below employee hierarchy table
Expected output:
For any given employee number, retrieve the manager hierarchy details till the HEAD/ROOT. Here is the output for employee number 14.
Query :
WITH HIER_QUERY AS ( SELECT EMPNO,ENAME,MGR FROM EMP START WITH EMPNO=11 CONNECT BY PRIOR MGR = EMPNO ) SELECT HQ.EMPNO "EMPLOYEE_ID", HQ.ENAME "EMPLOYEE_NAME", HQ.MGR "MANAGER_ID", E.ENAME "MANAGER_NAME" FROM HIER_QUERY HQ, EMP E WHERE E.EMPNO=HQ.MGR;
Employee Table Creation:
create table emp( empno number(4,0), ename varchar2(10), job varchar2(9), mgr number(4,0)); insert into emp values( 1, 'EMP1', 'HEAD', NULL); insert into emp values( 2, 'EMP2', 'EMPLEVEL1', 1); insert into emp values( 3, 'EMP3', 'EMPLEVEL1', 1); insert into emp values( 4, 'EMP4', 'EMPLEVEL1', 1); ---Under emp -2 insert into emp values( 5, 'EMP5', 'EMPLEVEL2', 2); insert into emp values( 6, 'EMP6', 'EMPLEVEL2', 2); insert into emp values( 7, 'EMP7', 'EMPLEVEL2', 2); --Under emp 3 insert into emp values( 8, 'EMP8', 'EMPLEVEL2', 3); insert into emp values( 9, 'EMP9', 'EMPLEVEL2', 3); --Under emp 3 insert into emp values( 10, 'EMP10', 'EMPLEVEL2', 4); insert into emp values( 11, 'EMP11', 'EMPLEVEL2', 4); --Under emp 6 insert into emp values( 12, 'EMP12', 'EMPLEVEL3', 6); insert into emp values( 13, 'EMP13', 'EMPLEVEL3', 6); --Under emp12 insert into emp values( 14, 'EMP14', 'EMPLEVEL4', 12); COMMIT;
No comments:
Post a Comment