SQL Update to the SUM of its joined values

后端 未结 7 1463
北恋
北恋 2020-12-04 17:42

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         


        
7条回答
  •  天涯浪人
    2020-12-04 18:07

    I ran into the same issue and found that I could solve it with a Common Table Expression (available in SQL 2005 or later):

    ;with cte as (
        SELECT PitchID, SUM(Price) somePrice
        FROM BookingPitchExtras
        WHERE [required] = 1 
        GROUP BY PitchID)
    UPDATE p SET p.extrasPrice=cte.SomePrice
    FROM BookingPitches p INNER JOIN cte ON p.ID=cte.PitchID
    WHERE p.BookingID=1
    

提交回复
热议问题