Home >Database >Mysql Tutorial >How Can I Use Aggregate Functions Like SUM in an SQL UPDATE Query?
Aggregate Function in an SQL Update Query
The question seeks to understand how aggregate functions, such as SUM, can be utilized in SQL update queries. The provided example attempts to update a value in a table based on the sum of values from another table. However, it encounters the limitation that SET statements do not support SUM and GROUP BY.
To resolve this issue, the solution employs a subquery to calculate the sum and then use the result in the update query. The following code snippet demonstrates the corrected approach:
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
In this corrected query:
By employing a subquery, this approach effectively addresses the limitations of SET statements and allows for the use of aggregate functions in update queries.
The above is the detailed content of How Can I Use Aggregate Functions Like SUM in an SQL UPDATE Query?. For more information, please follow other related articles on the PHP Chinese website!