SQL 更新查询中的聚合函数?
问题描述:
我试图将一个表中的值设置为另一个表中值的总和.一些类似的东西:
I'm trying to set the value in one table to the sum of the values in another table. Something along these lines:
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
>.
Of course, as this stands, it won't work - SET
doesn't support SUM
and it doesn't support GROUP BY
.
我应该知道这一点,但我的脑子里一片空白.我做错了什么?
I should know this, but my mind's drawing a blank. What am I doing wrong?
答
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