如何从SQL Server中的表中查找最新记录?

时间:2014-05-06 19:27:48

标签: sql sql-server tsql sql-server-2008-r2 sql-server-2012

我的EmployeeData表格如下所示

Employee    Jobnum    city   state   Datetime       Action
--------------------------------------------------------------------------    
Tom          123       mon    La     2014-04-14       U
Tom          123       mon    La     2014-04-14      D
Tom          123       mon    La     2014-04-13      D
Tom          124       tue    ca     2014-04-14      U
Tom          124       tue    ca     2014-04-14       I
Jerry        143       hr     NY     2014-04-14       D
Jerry        143       hr     NY     2014-04-14       I
Jerry        143       hr     NY     2014-04-14      I

当我查询该表时,我需要获取每位员工的最后记录。

输出应该看起来像

Employee    Jobnum    city   state   Datetime  Action
---------------------------------------------------------------------------
Tom          123       mon    La     2014-04-14     D
Tom          124       tue    ca     2014-04-14      I
Jerry        143       hr     NY     2014-04-14       I

2 个答案:

答案 0 :(得分:4)

SELECT Employee,Jobnum,city ,[state], [Datetime], [Action]
FROM (
select Employee,Jobnum,city ,[state], [Datetime], [Action]
       ,ROW_NUMBER() OVER (PARTITION BY Employee,Jobnum ORDER BY [Datetime] DESC) AS rn
from  EmployeeData
) Sub
WHERE rn = 1

注意

如果您确实有任何列名称是sql server中使用方括号[]的关键字,请避免使用Sql Server关键字作为列名。

答案 1 :(得分:1)

尝试一次

select ed.* 
from Employeedata ed
inner join
(
select jobnum,max(datetime) as maxdate
from Employeedata
group by jobnum
 ) X 
on ed.DATETIME = X.maxdate
and ed.jobnum = X.jobnum
order by ed.jobnum;

演示小提琴http://sqlfiddle.com/#!3/aa528/12