SQL UPDATE查询中的聚合函数。

我试图将一个表中的值设置为另一个表中的值之和。大概是这样的:

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

我应该知道的,但是我的脑子一片空白,我做错了什么?

112823 次浏览

用途:

UPDATE table1
SET field1 = (SELECT SUM(t2.field2)
FROM TABLE2 t2
WHERE t2.field3 = field2)
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天啊,小马的答案:

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

A good situation to use 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

我知道这个问题被标记为 SQLServer,但是如果您正在使用 PostgreSQL,请小心使用 JOIN 更新。@ JBrooks 回答不起作用:

UPDATE t1
SET t1.field1 = t2.field2Sum
FROM table1 t1
INNER JOIN (...) as t2
on t2.field3 = t1.field3

You will have to adapt it to :

UPDATE table1 t1
SET t1.field1 = t2.field2Sum
FROM (...) as t2
WHERE t2.field3 = t1.field3

See parameter from_list in the doc to get why FROM is considered by PostgreSQL as a self-join : https://www.postgresql.org/docs/9.5/static/sql-update.html#AEN89239

您也可以像下面这样使用 CTE。

;WITH t2 AS (
SELECT field3, SUM(field2) AS field2
FROM table2
GROUP BY field3
)
UPDATE table1
SET table1.field1 = t2.field2
FROM table1
INNER JOIN t2 ON table1.field3 = t2.field3