我有一个TempTable,其中包含表设置Empname SwipeTime和说明,如下所示
Mike 2019-05-17 12:00:16.383 User Granted Exit From Door Using Reading Device
Mike 2019-05-17 12:36:11.753 User Granted Entry To Door Using Reading Device
John 2019-05-17 12:00:16.383 User Granted Exit From Door Using Reading Device
John 2019-05-17 12:36:11.753 User Granted Entry To Door Using Reading Device
Steve 2019-05-17 12:00:16.383 User Granted Exit From Door Using Reading Device
Steve 2019-05-17 12:36:11.753 User Granted Entry To Door Using Reading Device
在所有人都有不同的滑动时间和描述的情况下,我如何才能获取每位员工的最新记录。
SELECT Distinct
MAX(EmployeeName) AS EmployeeName,
MAX(SwipeTime) AS MaxSwipeTime,
Description
FROM #WhosInOut
GROUP BY EmployeeName,Description, SwipeTime
ORDER BY EmployeeName, MAX(SwipeTime) ;
我希望列出所有具有最新记录的用户,而不是同时包含退出或进入记录
答案 0 :(得分:1)
我认为您想要row_number()
:
select t.*
from (select t.*, row_number() over (partition by employeename order by swipetime desc) as seq
from #WhosInOut t
) t
where seq = 1;
答案 1 :(得分:0)
您可以执行子查询:
SELECT a.*, b.Description
FROM
(SELECT Distinct
EmployeeName EmployeeName,
MAX(SwipeTime) AS MaxSwipeTime
FROM #WhosInOut
GROUP BY 1)a
JOIN #WhosInOut b
ON a.EmployeeName = b.EmployeeName and a.MaxSwipeTime = b.SwipeTime
ORDER by EmployeeName, MaxSwipeTime
答案 2 :(得分:0)
(可选)相关的子查询将起作用:
SELECT EmployeeName, SwipeTime, Description
FROM #WhosInOut t1
WHERE SwipeTime = (SELECT MAX(SwipeTime) FROM #WhosInOut WHERE t1.EmployeeName = EmployeeName)
答案 3 :(得分:0)
您可以使用row_number函数来提取最新的数据:
select x.empname, x.swipetime, x.description
from (
select a.empname, a.swipetime, a.description, ROW_NUMBER() (over partition by a.empname order by a.swipetime desc) as Ranks
from #whosinout a) x
where ranks = 1