2016年12月13日 星期二

SQL Update to the SUM of its joined values

在Master/Detail的架構下,要把子表的金額統計併到主表時的作法
BookingPitches 為主表
BookingPitchExtras 為子表
UPDATE p
SET 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

沒有留言: