SQL在历史记录表中的指定日期选择具有雇用状态的员工

时间:2013-05-27 16:16:18

标签: sql select

我有一个Employees表和一个EmploymentHistory表来记录他们的就业状况的变化。我希望能够选择一个在给定日期具有“雇佣”状态的所有员工的列表(例如,04/02/2013,这只会产生下面的John Smith)。

Employees       
employeeId    lastName    firstName
1             Smith       John
2             Doe         Jane
3             Carson      Mike

EmployeeHistory         
employeeHistoryId   employeeId    employmentStatus    transactionDate
1                   1             Hired               3/1/2013
2                   2             Candidate           4/1/2013
3                   2             Not Hired           4/5/2013
4                   3             Candidate           1/1/2013
5                   3             Hired               1/3/2013
6                   3             Terminated          2/15/2013

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您的数据库支持row_number(),您可以使用它来查找特定日期之前每位员工的最后一行。例如:

select  *
from    Employees e
join    (
        select  row_number() over (
                    partition by employeeId
                    order by transactionDate desc) as rn
        ,       employeeId
        ,       employmentStatus
        from    EmployeeHistory
        where   transactionDate < '2013-04-02'
        ) h
on      e.EmployeeId = h.EmployeeId
        and h.rn = 1 -- Only last row
where   h.employmentStatus = 'Hired'

Live example at SQL Fiddle.