web-dev-qa-db-fra.com

Mise à jour SQL vers la somme de ses valeurs jointes

J'essaie de mettre à jour un champ de la base de données à la somme de ses valeurs jointes:

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

Lorsque j'exécute cela, j'obtiens l'erreur suivante:

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

Des idées?

44
markvpc

Que dis-tu de ça:

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
62
JonH

Une alternative aux solutions ci-dessus utilise des alias pour les tables:

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

Ceci est une erreur valide. Voir ceci . Voici (et d'autres suggérées ci-dessous) les moyens d'y parvenir: -

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
2
Ashish Gupta

J'ai rencontré le même problème et j'ai trouvé que je pouvais le résoudre avec Common Table Expression (disponible dans SQL 2005 ou version ultérieure):

;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
1
C-Pound Guru

Avec postgres, j'ai dû ajuster la solution avec ça pour que ça marche pour moi:

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
1
Yoric

Utilisez une sous-requête similaire à celle ci-dessous.

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
0
cmsjr

Vous avez besoin de quelque chose comme ça:

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
0
MartW