Oracle SQL:按最近日期检索记录

时间:2018-06-08 18:13:33

标签: sql oracle

我正在尝试使用最新的ROLE_START_DATE提取记录的详细信息。我已经尝试了多种方法,并且无法让它发挥作用。它总是最终拉出所有数据,而不是特定的记录。

基本脚本:

SELECT DISTINCT EMPLOYEE "E.EMPLOYEE #",
LR.DESCRIPTION "Role", 
R.ROLE_STATUS "Status",
R.ROLE_START_DATE "Role Start"
FROM EMPLOYEES E
JOIN ROLES R ON E.EMPLOYEE_ID = R.EMPLOYEE_ID
JOIN LU_ROLES LR ON R.ROLE_ID = LR.ROLE_ID
WHERE ROLE_START_DATE <= DATE '2017-12-03'
ORDER BY 1

结果:

Employee #  |   Role  |  Status  |  Role Start
23432        Associate  Not Active 04/23/2011    
23432        Manager    Active     11/2/2012
54334        Analyst    Resigned   10/15/2015
12311        Help Desk  Not Active 05/12/2014
12311        Analyst    Not Active 06/11/2015
12311        Supervisor Active     07/12/2016

修改为仅提取具有最新日期的记录,但它不能按预期工作,并且给出与上面完全相同的回报。

SELECT DISTINCT EMPLOYEE "E.EMPLOYEE #",
LR.DESCRIPTION, 
R.ROLE_STATUS,
MAX(ROLE_START_DATE)
FROM EMPLOYEES E
JOIN ROLES R ON E.EMPLOYEE_ID = R.EMPLOYEE_ID
JOIN LU_ROLES LR ON R.ROLE_ID = LR.ROLE_ID
WHERE ROLE_START_DATE >= DATE '2017-12-03'
GROUP BY E.EMPLOYEE, LR.DESCRIPTION, R.ROLE_STATUS
ORDER BY 1

我想得到什么:

Employee #  |   Role  |  Status  |  Role Start
23432        Manager    Active     11/2/2012
54334        Analyst    Resigned   10/15/2015
12311        Supervisor Active     07/12/2016

非常感谢任何帮助或建议。

提前致谢!

3 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是使用窗口函数(Oracle术语分析函数)。如果您想要返回关系(具有相同开始日期的多个角色的员工),请使用RANK()DENSE_RANK();如果您想要一个具有最新开始日期的任意角色,请使用ROW_NUMBER()

SELECT employee AS "E.EMPLOYEE #"
     , description AS "Role"
     , role_status AS "Status"
     , role_start_date "Role Start"
  FROM (
    SELECT e.employee, lr.description, r.role_status, r.role_start_date
         , RANK() OVER ( PARITION BY e.employee ORDER BY r.role_start_date DESC ) AS rn
      FROM employees e INNER JOIN roles r
        ON e.employee_id = r.employee_id
     INNER JOIN lu_roles lr
        ON lr.role_id = r.role_id
     WHERE r.role_start_dt >= DATE'2017-12-03'
) WHERE rn = 1;

希望这有帮助。

答案 1 :(得分:0)

看看这是否有帮助 -

SELECT * FROM (
SELECT DISTINCT EMPLOYEE "E.EMPLOYEE #",
LR.DESCRIPTION "Role", 
R.ROLE_STATUS "Status",
R.ROLE_START_DATE "Role Start",
DENSE_RANK() OVER (PARTITION BY EMPLOYEE ORDER BY ROLE_START_DATE DESC) AS RNK
FROM EMPLOYEES E
JOIN ROLES R ON E.EMPLOYEE_ID = R.EMPLOYEE_ID
JOIN LU_ROLES LR ON R.ROLE_ID = LR.ROLE_ID
WHERE ROLE_START_DATE >= DATE '2017-12-03'
ORDER BY 1
) WHERE RNK = 1

答案 2 :(得分:0)

您可以将ROW_NUMBER/RANKFETCH FIRST ... WITH TIES结合使用(Oracle 12c):

SELECT e.employee, lr.description, r.role_status, r.role_start_date
FROM employees e 
JOIN roles r
  ON e.employee_id = r.employee_id
JOIN lu_roles lr
  ON lr.role_id = r.role_id
 WHERE r.role_start_dt >= DATE'2017-12-03'
ORDER BY RANK() OVER (PARITION BY e.employee ORDER BY r.role_start_date DESC)
FETCH FIRST 1 ROW WITH TIES;