使用原始表中的条件从一个表中使用多个子查询来更新查询

问题描述 投票:0回答:2

我有以下查询来从我的

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
或一般优化此查询?

sql subquery correlated-subquery sql-server-2019
2个回答
1
投票

您可以使用 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;

0
投票

这是我当前的解决方案:

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;
© www.soinside.com 2019 - 2024. All rights reserved.