我的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
答案 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;