SQL更新为其join的值的SUM

我试图将数据库中的一个字段更新为其join的值的总和:

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 

当我运行这个我得到以下错误:

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

有任何想法吗?

这个怎么样:

 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 

上述解决scheme的一个替代方法是使用表的别名:

 UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID) FROM BookingPitches T1; 

这是一个有效的错误。 看到这个 以下(和其他人build议下面)是实现这一目标的方法:

 UPDATE P SET extrasPrice = t.TotalPrice FROM BookingPitches AS P INNER JOIN ( SELECT PitchID, SUM(Price) TotalPrice FROM BookingPitchExtras GROUP BY PitchID ) t ON t.PitchID = p.ID 

使用类似于下面的子查询。

 UPDATE P SET extrasPrice = sub.TotalPrice from BookingPitches p inner join (Select PitchID, Sum(Price) TotalPrice from dbo.BookingPitchExtras Where [Required] = 1 Group by Pitchid ) as Sub on p.Id = e.PitchId where p.BookingId = 1 

你需要这样的东西:

 UPDATE P SET ExtrasPrice = E.TotalPrice FROM dbo.BookingPitches AS P INNER JOIN (SELECT BPE.PitchID, Sum(BPE.Price) AS TotalPrice FROM BookingPitchExtras AS BPE WHERE BPE.[Required] = 1 GROUP BY BPE.PitchID) AS E ON P.ID = E.PitchID WHERE P.BookingID = 1 

我遇到了同样的问题,发现我可以使用通用expression式 (在SQL 2005或更高版本中可用)解决它:

 ;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 

有了postgres,我不得不调整解决scheme,为我工作:

 UPDATE BookingPitches AS p SET extrasPrice = t.sumPrice FROM ( SELECT PitchID, SUM(Price) sumPrice FROM BookingPitchExtras WHERE [required] = 1 GROUP BY PitchID ) t WHERE t.PitchID = p.ID AND p.bookingID = 1