如何从同一列同时更新母马行?

时间:2017-12-21 17:02:17

标签: sql sql-server sql-update

我有这张桌子:

How the table looks

我想更新列Distance以确定子查询所有记录的距离where name='drive_through'

这是预期的结果:

This should be the expected result

到目前为止,我已经完成了这项工作,但我不明白如何在单个查询中为每一行进行更新

UPDATE Action
SET [distance] = (SELECT [distance]
                  FROM Action
                  WHERE [name] = 'travel')
WHERE [name] = 'drive_through'

问题:如果我想要所有者ID相同的第二条记录,如上面所有者ID为9690的屏幕截图,距离pe 0.000而不是72.841,我应该如何修改查询?

3 个答案:

答案 0 :(得分:3)

据推测,您需要一个相关的子查询。我猜:

UPDATE Action
    SET [distance] = (SELECT SUM([distance])
                      FROM Action a2
                      WHERE [name] = 'travel' AND a2.ownerID = Action.ownerId
                    )
   WHERE [name] = 'drive_through';

答案 1 :(得分:1)

您有两种选择:

:一种。关联子查询。这意味着添加一行将您正在更新的行连接到子查询中的一行(因为当前子查询将返回许多行,因此错误):

UPDATE A
SET [distance] = (SELECT DISTINCT [distince]
                  FROM Action A2
                  WHERE [name] = 'Travel'
                  AND A.ownerID = A2.ownerID) --Here
FROM Action A
WHERE [name] = 'drive_through'

<强> B中。使用联接

UPDATE A
SET A.[distince] = A2.[distance]
FROM Action A
JOIN Action A2 ON A.ownerID = A2.ownerID
WHERE A.name = 'drive_through'
AND A2.name = 'Travel'

答案 2 :(得分:0)

一种可能的解决方案是将JOIN与同一个表的另一个实例一起使用。

UPDATE a1 
SET a1.distance = a2.distance 
FROM Action a1 
JOIN Action a2 ON a1.OwnerID = a2.OwnerID 
WHERE a1.name = 'drive_through'