SQL UPDATE 当有两个相同的值时,将一列设置为等于 0.000
SQL UPDATE SET one column to be equal to 0.000 when there are two identical values
所以这是我尝试更新列距离的问题,首先对每个 ownerID 的距离求和,然后当存在具有相同 ID 地址的记录时,第一个记录应该记忆你的距离,第二个应该为 0.000
这是预期的结果
到目前为止,我已经完成了使用此代码计算距离的第一部分
UPDATE Action_Distance
SET [distance]=(SELECT sum([distance])
FROM Action a2
WHERE [name]='travel' and a2.ownerID = Action_Distance.ownerId
)
WHERE [name]='drive_through'
我不明白应该怎么做。
假设 id_action
对于每一行都是唯一的,那么 CASE
表达式和 NOT EXIST
子查询可以这样使用:
UPDATE Action_Distance A
SET [distance] = CASE
WHEN NOT EXISTS (SELECT 'anything'
FROM Action_Distance B
WHERE B.[name] = 'drive_through'
AND a.ownerId = b.ownerId
AND a.id_action > b.id_action)
THEN (SELECT SUM([distance])
FROM Action a2
WHERE [name] = 'travel'
AND a2.ownerID = a.ownerId)
ELSE 0
END
WHERE
[name] = 'drive_through'
所以这是我尝试更新列距离的问题,首先对每个 ownerID 的距离求和,然后当存在具有相同 ID 地址的记录时,第一个记录应该记忆你的距离,第二个应该为 0.000
这是预期的结果
到目前为止,我已经完成了使用此代码计算距离的第一部分
UPDATE Action_Distance
SET [distance]=(SELECT sum([distance])
FROM Action a2
WHERE [name]='travel' and a2.ownerID = Action_Distance.ownerId
)
WHERE [name]='drive_through'
我不明白应该怎么做。
假设 id_action
对于每一行都是唯一的,那么 CASE
表达式和 NOT EXIST
子查询可以这样使用:
UPDATE Action_Distance A
SET [distance] = CASE
WHEN NOT EXISTS (SELECT 'anything'
FROM Action_Distance B
WHERE B.[name] = 'drive_through'
AND a.ownerId = b.ownerId
AND a.id_action > b.id_action)
THEN (SELECT SUM([distance])
FROM Action a2
WHERE [name] = 'travel'
AND a2.ownerID = a.ownerId)
ELSE 0
END
WHERE
[name] = 'drive_through'