我正在处理一个Oracle查询,该查询包含以下数据:
Emp Designation reporter
A Director
B Manager A
C Supervisor B
F Supervisor A
G Director
H Emp B
P Supervisor B
Q Manager G
层次结构是: 导向器 经理 监 EMP
在上表中,我们缺少关系。 例如。在第4次记录中,经理失踪了,' F' (主管)直接报告' A' (导向器) 在第6个记录中,主管缺失,' H'(Emp)直接向' B' (经理) 我正在尝试构建oracle查询以获得以下结果:
Director Manager Supervisor Emp
A B C
A F
G Q
A B H
B P
select a.emp Director, b.emp Supervisor , c.emp manager, d.emp emp
from
hr_test a
left join hr_test b
on a.emp = b.reporter
left join
hr_test c
on b.emp = c.reporter
left join
hr_test d
on c.emp = d.reporter
where a.DESIGNATION = 'Director'
但是通过上述查询,我得不到失踪的关系。
如果有人帮助我,我将非常感激。 提前谢谢。
答案 0 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE hr_test ( Emp, Designation, reporter ) AS
SELECT 'A', 'Director', NULL FROM DUAL UNION ALL
SELECT 'B', 'Manager', 'A' FROM DUAL UNION ALL
SELECT 'C', 'Supervisor', 'B' FROM DUAL UNION ALL
SELECT 'F', 'Supervisor', 'A' FROM DUAL UNION ALL
SELECT 'G', 'Director', NULL FROM DUAL UNION ALL
SELECT 'H', 'Emp', 'B' FROM DUAL UNION ALL
SELECT 'P', 'Supervisor', 'B' FROM DUAL UNION ALL
SELECT 'Q', 'Manager', 'G' FROM DUAL;
查询1 :
SELECT Director,
Manager,
Supervisor,
Emp
FROM (
SELECT CONNECT_BY_ROOT( Emp ) AS root,
Designation,
Emp
FROM hr_test t
START WITH emp NOT IN ( SELECT reporter FROM hr_test WHERE reporter IS NOT NULL )
CONNECT BY PRIOR reporter = emp
)
PIVOT ( MAX( Emp ) FOR Designation IN (
'Director' AS DIRECTOR,
'Manager' AS MANAGER,
'Supervisor' AS SUPERVISOR,
'Emp' AS EMP
)
)
<强> Results 强>:
| DIRECTOR | MANAGER | SUPERVISOR | EMP |
|----------|---------|------------|--------|
| A | B | (null) | H |
| A | B | P | (null) |
| G | Q | (null) | (null) |
| A | B | C | (null) |
| A | (null) | F | (null) |