使用oracle查询获取每个员工的上次更新时间

时间:2013-04-03 14:19:26

标签: sql oracle

我已经尝试了以下查询来获取最后一次更新值..但我不能为每位员工获得单行

select distinct Employee_name,Employee_status,update_time
  from Employee 
 where Employee_name= 'Muthukumar'
   and Employee_status='ACTIVE' 
 order by Employee_name, Update_time desc

Employee_name       Employee_status  Update_time
Muthukumar          ACTIVE           06-DEC-12 10.18.59.048000000 AM
Muthukumar          ACTIVE           05-DEC-12 05.05.41.165000000 AM
Muthukumar          ACTIVE           04-SEP-12 03.00.54.706000000 AM

像这样,我将为不同的员工提供参赛作品。我需要为每个员工提供一行,只有最后更新时间。(最高)

输出应为:

Employee_name  Employee_status   Update_time
Muthukumar     ACTIVE            06-DEC-12 10.18.59.048000000 AM

2 个答案:

答案 0 :(得分:1)

Oracle支持common table expressionwindow function。在使用ROW_NUMBER()的帮助下,它根据特定顺序对组中的每条记录进行排名。

WITH empList
AS
(
    SELECT  Employee_Name,
            Employee_Status,
            Update_Time,
            ROW_NUMBER() OVER(PARTITION BY Employee_Name
                                ORDER BY Update_Time DESC) rn
    FROM    EmployeeList
)
SELECT  Employee_Name,
        Employee_Status,
        Update_Time
FROM    empList
WHERE   rn = 1

答案 1 :(得分:0)

这是一个经典的分析排名请求。您需要按员工划分所有行并按日期排序。然后只采取第一个排名。

有些人阅读herehere

SELECT Employee_name, Employee_status, update_time  
FROM
(
    SELECT Employee_name, Employee_status, update_time,
           RANK() OVER (PARTITION BY Employee_name ORDER BY update_time DESC) as Rank
    FROM Employee
)
WHERE Rank = 1