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?
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.
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With