Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate function in an SQL update query?

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 

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?

like image 971
Margaret Avatar asked Jan 05 '10 23:01

Margaret


People also ask

Can we use aggregate function in UPDATE statement?

An aggregate may not appear in the set list of an UPDATE statement. But SQL doesn't always agree that it should be simple. Let's setup a contrived example using a data set of Airport Gate information from San Francisco Airport. I have 1 table which has all of the times a Gate has been used at the airport.

How do I use GROUP BY in UPDATE query?

You can't issue an UPDATE statement using a group by. The point of using GROUP BY is to change the way that the result set is displayed to the user. When you have a GROUP BY statement you utilize the HAVING clause to filer the aggregated result set.

When an aggregate function is used in a SQL query?

An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function ignores NULL values when it performs the calculation, except for the count function.

Can we use aggregate function with query syntax?

Except for the COUNT() function, SQL aggregate functions ignore null. You can use aggregate functions as expressions only in the following: The select list of a SELECT statement, either a subquery or an outer query.


2 Answers

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   
like image 68
JBrooks Avatar answered Oct 05 '22 12:10

JBrooks


Use:

UPDATE table1    SET field1 = (SELECT SUM(t2.field2)                     FROM TABLE2 t2                    WHERE t2.field3 = field2) 
like image 42
OMG Ponies Avatar answered Oct 05 '22 11:10

OMG Ponies