这是一个常见的问题,但从我浏览的问题中,我无法找到一个好的答案。对于每个员工,我想显示他们最后一次已知的状态和该状态的时间。
我有两个SQL Server表(实际上他们是视图):
员工
EmployeeID | Name | 123 | xyz |
---|
我认为合理的写法如下:
WITH c AS (
SELECT clock.*, row_number() OVER (PARTITION BY employeeid ORDER BY time DESC) rn
FROM clock
)
SELECT
e.EmployeeID,
c.Time LastClock,
c.Clocktype
FROM Employee e
LEFT JOIN c ON e.EmployeeID = c.EmployeeID
WHERE COALESCE(c.rn, 1) = 1
然而,我认为对于这个(或您的原始查询)的性能最重要的事情是确保您在clock
(employeeid
,time
)上有适当的索引。例:create index ix_clock on clock (employeeid, time)
为了获得更好的性能,可以使用下面的查询来获得相同的结果,以优化性能。
SELECT e.EmployeeID, c.Time AS LastClock, c.ClockType
FROM Employee e
LEFT JOIN (
SELECT EmployeeID, Time, ClockType
FROM Clock
WHERE Time = (SELECT MAX(Time) FROM Clock c1 WHERE c1.EmployeeID = Clock.EmployeeID)
) c ON e.EmployeeID = c.EmployeeID