SQL更新查询中的聚合函数?

我试图将一个表中的值设置为另一个表中的值的总和。 沿着这些线路的东西:

UPDATE table1 SET field1 = SUM(table2.field2) FROM table1 INNER JOIN table2 ON table1.field3 = table2.field3 GROUP BY table1.field3 

当然,这样做,它不会工作 – SET不支持SUM ,它不支持GROUP BY

我应该知道这一点,但是我的想法是空白的。 我究竟做错了什么?

 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 

使用:

 UPDATE table1 SET field1 = (SELECT SUM(t2.field2) FROM TABLE2 t2 WHERE t2.field3 = field2) 

或者你可以使用JBrooks和OMG小马混合的答案:

 UPDATE table1 SET field1 = (SELECT SUM(field2) FROM table2 AS t2 WHERE t2.field3 = t1.field3) FROM table1 AS t1 

很好的情况下使用CROSS APPLY

 UPDATE t1 SET t1.field1 = t2.field2Sum FROM table1 t1 CROSS APPLY (SELECT SUM(field2) as field2Sum FROM table2 t2 WHERE t2.field3 = t1.field3) AS t2