当有两个相同的值时,SQL UPDATE SET一列等于0.000

时间:2017-12-21 21:28:05

标签: sql sql-update sql-server-2014-express

所以这就是我试图更新列距离的问题,首先要对每个ownerID的距离求和,之后当有一个具有相同id地址的记录时,第一条记录应该记住距离而第二条应该记住距离是0.000

这是预期的结果

enter image description here

到目前为止,我做了第一部分使用此代码计算距离

UPDATE Action_Distance
SET [distance]=(SELECT sum([distance])
               FROM Action a2
               WHERE [name]='travel' and a2.ownerID = Action_Distance.ownerId 
               )

               WHERE [name]='drive_through' 

我不明白应该怎么做。

1 个答案:

答案 0 :(得分:0)

假设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'