我有一个包含许多行的表,我希望有一种方法可以更新此表中根据另一个表的总和计算的总成本列。
是否可以按照以下方式做点什么:
UPDATE [PO] set TotalCost=(Select sum(Cost) from [PO-Lines] where PO=Update.PO)
这样我就不必创建循环
了答案 0 :(得分:1)
我不知道SQL-Server,所以我从MySQL推断并希望我得到正确的语法。你可以通过JOIN:
来做到这一点UPDATE t1
SET t1.TotalCost = t2.Total
FROM [PO] AS t1
JOIN (SELECT POId, SUM(Cost) Total
FROM [POLines]
GROUP BY POId) AS t2
ON t1.ID = t2.POId
或相关子查询:
UPDATE [PO]
SET TotalCost = (SELECT SUM(Cost) FROM [PO-Lines] WHERE [PO-Lines].POId = [PO].ID)