甲骨文:分层查询连接方式

Oracle : Hierarchical Query Connect By

我编写了一个 Oracle 层次结构查询,它将为我们提供特定员工的高层管理人员。

例如 如果我们有示例 Emp 和 Manager 映射,例如:

WITH emp_manager_mapping AS (
 select 'A' empId, 'B' managerId,sysdate-100 appliedOn,'Success' status from dual
 union all
 select 'C' empId, 'D' managerId, sysdate-70 appliedOn, 'Success' status from dual
  union all
 select 'B' empId, 'C' managerId, sysdate-50 appliedOn,'Success' status from dual
 )select * from emp_manager_mapping; 

输出为:

A   B   10-SEP-19   Success
C   D   10-OCT-19   Success
B   C   30-OCT-19   Success

之后我们对该数据集应用分层查询 what to find who is top manager of Employee id "A" than:

WITH emp_manager_mapping AS (
 select 'A' empId, 'B' managerId,sysdate-100 appliedOn,'Success' status from dual
 union all
 select 'C' empId, 'D' managerId, sysdate-70 appliedOn, 'Success' status from dual
  union all
 select 'B' empId, 'C' managerId, sysdate-50 appliedOn,' Success' status from dual
 ) SELECT
    CONNECT_BY_ROOT ( empid ) AS empid,
    CONNECT_BY_ROOT ( managerid ) AS managerid,
    managerid AS top_manager_id,
    level
FROM
    emp_manager_mapping
WHERE
    CONNECT_BY_ISLEAF = 1 and status = 'Success'
START WITH
    empid = 'A'
CONNECT BY NOCYCLE
    PRIOR managerid = empid;

比输出为:

Value of top_manager_id is D

根据查询,它提供查询但不提供申请日期,如果我们考虑最新的申请日期也比我们必须忽略

C   D   10-OCT-19   Success record.

我希望最终输出 top_manager id 应该是 "C"

任何人都可以帮助找到预期的结果吗?

查找层次结构中的所有行,然后按 appliedOn 对这些行进行排序并仅保留最新行:

查询:

WITH emp_manager_mapping ( empid, managerid, appliedon, status ) AS (
  select 'A', 'B', sysdate-100,'Success' from dual union all
  select 'C', 'D', sysdate-70, 'Success' from dual union all
  select 'B', 'C', sysdate-50, 'Success' from dual
)
SELECT managerid AS top_managerid,
       LEVEL AS depth,
       CONNECT_BY_ROOT ( empid ) AS empid,
       CONNECT_BY_ROOT ( managerid ) AS managerid
FROM   emp_manager_mapping e
WHERE  status = 'Success'
START WITH empid = 'A'
CONNECT BY NOCYCLE
       PRIOR managerid = empid
ORDER BY AppliedOn DESC
FETCH FIRST ROW ONLY;

输出:

TOP_MANAGERID | DEPTH | EMPID | MANAGERID
:------------ | ----: | :---- | :--------
C             |     2 | A     | B        

db<>fiddle here