Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update to the SUM of its joined values

I'm trying to update a field in the database to the sum of its joined values:

UPDATE P SET extrasPrice = SUM(E.price) FROM dbo.BookingPitchExtras AS E INNER JOIN dbo.BookingPitches AS P ON E.pitchID = P.ID     AND P.bookingID = 1 WHERE E.[required] = 1 

When I run this I get the following error:

"An aggregate may not appear in the set list of an UPDATE statement." 

Any ideas?

like image 955
Mark Clancy Avatar asked Mar 23 '10 17:03

Mark Clancy


People also ask

Can we use UPDATE with joins?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

Can we use aggregate functions 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 sum rows together in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.


2 Answers

How about this:

UPDATE p SET p.extrasPrice = t.sumPrice FROM BookingPitches AS p INNER JOIN     (         SELECT PitchID, SUM(Price) sumPrice         FROM BookingPitchExtras         WHERE [required] = 1         GROUP BY PitchID      ) t     ON t.PitchID = p.ID WHERE p.bookingID = 1 
like image 196
JonH Avatar answered Sep 19 '22 12:09

JonH


An alternate to the above solutions is using Aliases for Tables:

UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID) FROM BookingPitches T1; 
like image 29
Muhammad Omar ElShourbagy Avatar answered Sep 19 '22 12:09

Muhammad Omar ElShourbagy