Aggregate function in an SQL update query?

前端 未结 6 1847
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 10:48

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.fiel         


        
6条回答
  •  余生分开走
    2020-12-02 11:20

    I know the question is tagged SQL Server but be careful with UPDATE with JOIN if you are using PostgreSQL. @JBrooks answer won't work :

    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

提交回复
热议问题