根据表中的日期查找最新记录

时间:2017-09-27 13:45:36

标签: sql-server sql-server-2008

不确定如何在没有特定于我的数据的情况下放置它 - 我想根据表格中的日期找到每个人的最新值

PayHistory表

PayHistoryID, EmployeeID,  Date,        PayRate
1,            1,          '2017-01-01', 20000
2,            2,          '2017-01-01', 21000
3,            3,          '2017-01-01', 22000
4,            3,          '2017-05-01', 24000
5,            4,          '2017-01-01', 20000
6,            4,          '2017-06-01', 24000

员工表

EmployeeID, EmployeeName
1,          Bob
2,          Frank
3,          Jess 
4,          Alex

我想带回来

EmployeeID, EmployeeName
1,          20000
2,          21000
3,          24000 
4,          24000

4 个答案:

答案 0 :(得分:2)

ROW_NUMBER()是要走的路:

select
    EmployeeID
    ,PayRate
from
(
    select
        rownum = row_number() over(partition by EmployeeID order by ph.[Date] desc)
        ,e.EmployeeID
        ,PayRate
    from EmployeeTable e
        inner join PayHistoryTable ph on e.EmployeeID = ph.EmployeeID
) x
where rownum = 1

答案 1 :(得分:2)

使用FIRST_VALUE:

create table #PayHistory (PayHistoryID int, EmployeeID int, [Date] date, PayRate int)

insert into #PayHistory values(1, 1, '2017-01-01', 20000)
insert into #PayHistory values(2, 2, '2017-01-01', 21000)
insert into #PayHistory values(3, 3, '2017-01-01', 22000)
insert into #PayHistory values(4, 3, '2017-05-01', 24000)
insert into #PayHistory values(5, 4, '2017-01-01', 20000)
insert into #PayHistory values(6, 4, '2017-06-01', 24000)

select distinct EmployeeID, FIRST_VALUE(PayRate) OVER (Partition by EmployeeID order by [date] desc) from #PayHistory

2012年之前版本的等价物:

select distinct ph.EmployeeID
   , (Select top 1 Payrate from #PayHistory where EmployeeID = ph.EmployeeID ORDER BY [DATE] desc) as [PayRate]
from #PayHistory ph

答案 2 :(得分:1)

您应该使用OUTER APPLY:

SELECT *
FROM Employee E
OUTER APPLY (SELECT TOP 1 PayRate FROM PayHistory PH WHERE PH.EmployeeID = 
E.EmployeeID ORDER BY [date] DESC) T

答案 3 :(得分:0)

你sohuld使用ROW_NUMBER列出你的行,只选择第一行。 这里有一个查询表的例子,希望这有帮助;

Select EmployeeID,PayRate FROM (
Select ROW_NUMBER() OVER(Partition By e.EmployeeID Order By [DATE] DESC) AS RN,e.EmployeeID,PayRate FROM @employee e
INNER JOIN @payHistory p on p.EmployeeID = e.EmployeeID
) as P
Where RN = 1