Answers:
UPDATE t1
SET t1.field1 = t2.field2Sum
FROM table1 t1
INNER JOIN (select field3, sum(field2) as field2Sum
from table2
group by field3) as t2
on t2.field3 = t1.field3
或者您可以混合使用JBrooks和OMG Ponies答案:
UPDATE table1
SET field1 = (SELECT SUM(field2)
FROM table2 AS t2
WHERE t2.field3 = t1.field3)
FROM table1 AS t1
我知道问题被标记为SQL Server,但是如果您使用PostgreSQL,请谨慎使用UPDATE与JOIN 。@JBrooks答案无效:
UPDATE t1
SET t1.field1 = t2.field2Sum
FROM table1 t1
INNER JOIN (...) as t2
on t2.field3 = t1.field3
您必须将其调整为:
UPDATE table1 t1
SET t1.field1 = t2.field2Sum
FROM (...) as t2
WHERE t2.field3 = t1.field3
请参阅from_list
文档中的参数以获取为什么FROM
PostgreSQL认为它是自连接的:https : //www.postgresql.org/docs/9.5/static/sql-update.html#AEN89239