我正在尝试将数据库中的字段更新为其连接值的总和:
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."
有什么想法吗?
答案 0 :(得分:59)
这个怎么样:
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
答案 1 :(得分:8)
上述解决方案的替代方案是使用表的别名:
UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;
答案 2 :(得分:2)
这是一个有效的错误。见this。以下(以及其他建议如下)是实现这一目标的方法: -
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
答案 3 :(得分:1)
我遇到了同样的问题,发现我可以用Common Table 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
答案 4 :(得分:1)
使用postgres,我不得不调整解决方案,以便为我工作:
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
答案 5 :(得分:0)
使用类似于下面的子查询。
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
答案 6 :(得分:0)
你需要这样的东西:
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