我有以下查询来从我的
Records
表中获取多个设备的最新 GPS 记录:
DECLARE @Result TABLE
(DeviceID int, RecordID int, DeviceTime datetime, Own bit, New bit, ...);
--insert a few device IDs into @Result and set New = 0 and Own to 0 or 1
--then:
UPDATE @Result
SET New = 1,
RecordID = (SELECT TOP(1) ID FROM Records WHERE Records.Device_ID = [@Result].DeviceID ORDER BY Records.DeviceTime DESC),
GPSTime = (SELECT TOP(1) DeviceTime FROM Records WHERE Records.Device_ID = [@Result].DeviceID ORDER BY Records.DeviceTime DESC)
WHERE Own = 1;
有没有一种方法可以通过一个子查询从
ID
中选择 DeviceTime
和 Records
或一般优化此查询?
您可以使用 CTE 将其表述为更新连接:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Device_ID
ORDER BY DeviceTime DESC) rn
FROM Records
)
UPDATE a
SET New = 1,
RecordID = b.ID,
GPSTime = b.DeviceTime
FROM @Result a
INNER JOIN cte b
ON b.Device_ID = a.DeviceID
WHERE a.Own = 1 AND b.rn = 1;
这是我当前的解决方案:
UPDATE @Result
SET New = 1, RecordID = R.ID, GPSTime = R.DeviceTime
FROM @Result
CROSS APPLY
(SELECT TOP(1) ID, DeviceTime FROM Records WHERE Records.Device_ID = [@Result].DeviceID ORDER BY Records.DeviceTime DESC) AS R
WHERE Own = 1;