gpt4 book ai didi

sql - 甲骨文 : Hierarchical Query Connect By

转载 作者:行者123 更新时间:2023-12-02 02:41:06 25 4
gpt4 key购买 nike

我编写了一个 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 来查找员工 ID“A”的最高经理是谁:

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

关于sql - 甲骨文 : Hierarchical Query Connect By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59415657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com