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

时间:2010-01-05 23:25:47

标签: sql sql-server tsql

我正在尝试将一个表中的值设置为另一个表中值的总和。这些方面的东西:

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

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

6 个答案:

答案 0 :(得分:138)

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  

答案 1 :(得分:9)

使用:

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

答案 2 :(得分:5)

或者您可以混合使用JBrooksOMG Ponies个答案:

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

答案 3 :(得分:3)

使用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

答案 4 :(得分:2)

我知道问题是标记为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,了解PostgreSQL将FROM视为自我加入的原因:https://www.postgresql.org/docs/9.5/static/sql-update.html#AEN89239

答案 5 :(得分:1)

您还可以像下面那样使用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