情景是: - 乔伊斯是一名MGR,向帕姆报道。格雷格是向乔伊斯汇报的MGR,因此汇总到了帕姆。
因此,对于一个非常高级别的人,您将看到所有与该查询直接或间接相关的报告者。
包含TABLE_MGR信息的表: -
Employee MGR
Joyce PAM
GREG JOYCE
所以期望的输出将是
Employee MGR
Joyce PAM
GREG PAM
如何实现这一目标?
答案 0 :(得分:1)
您可以将connect by
子句与connect_by_root
一起使用。
实施例
create table tmp_emp as
select 'JOYCE' employee, 'PAM' mgr from dual
union
select 'GREG' employee, 'JOYCE' mgr from dual;
select level, CONNECT_BY_root mgr root_mgr, t.*
from tmp_emp t
start with mgr = 'PAM'
connect by nocycle prior employee = mgr;
输出
LEVEL ROOT_MGR EMPLOYEE MGR
---------- -------- -------- -----
1 PAM JOYCE PAM
2 PAM GREG JOYCE
2 rows selected.
修改强>
无需使用start with
。这也可行
select level, CONNECT_BY_root mgr root_mgr, t.*
from tmp_emp t
connect by nocycle prior employee = mgr;
但也许你只希望没有经理的员工能够做到这一点。它还向您显示最高管理者的层次结构。
with roots as
(
select level lvl, CONNECT_BY_root mgr root_mgr, employee, SYS_CONNECT_BY_PATH(mgr, '/') "Path"
from tmp_emp t
connect by prior employee = mgr
)
select *
from roots r1
where root_mgr not in (select employee from roots r2 );
输出
LVL ROOT_MGR EMPLOYEE Path
---------- -------- -------- -------------
2 PAM GREG /PAM/JOYCE
1 PAM JOYCE /PAM