tags:

views:

209

answers:

4

Hi, 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?

+2  A: 

How about this:

    UPDATE P 
    SET extrasPrice = t.somePrice
    FROM BookingPitches AS P INNER JOIN
     (
      SELECT
        PitchID,
        SUM(Price) somePrice
      FROM
         BookingPitchExtras
      WHERE [required] = 1 
      GROUP BY PitchID
      ) t
    ON t.PitchID = p.ID
WHERE
    P.bookingID = 1 
JonH
A: 

Use a sub query similar to the below.

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
cmsjr
A: 

You need something like this :

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
CodeByMoonlight
A: 

This is a valid error. See this. Following (and others suggested below) are the ways to achieve 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
ydobonmai
@Ashish Gupta - Looks a lot like my query...hmm
JonH
ooops...sorry..Want me to delete the answer? I didnot load the answer when I was writing the query and was reading that article.
ydobonmai
@Ashish - No that is fine I just thought it was odd that we even used the same temp storage t, and the query was quite almost exactly the same. 2 answers are better then 1.
JonH
JonH, I will learn to load the answers while I am writing answers. Sorry again. Didn't mean that. I edited my answer as well.
ydobonmai