Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update with the value returned from aggregate function

Tags:

sql

How to update a column of a table using an aggregate function in the sql update statement ?

like image 777
nikethan Avatar asked Apr 26 '26 07:04

nikethan


1 Answers

Aggregate function, by definition, aggregates one or more records of the input into a single record in a resultset, so it is not obvious which one you want to update.

In general, you can use aggregate functions in a subquery:

UPDATE  mytable
SET     mycol = 
        (
        SELECT  SUM(othercol)
        FROM    othertable o
        WHERE   o.yetothercol = m.yetmycol
        )

, in a JOIN (works in MySQL and SQL Server)

UPDATE  mytable
JOIN    (
        SELECT  yetothercol, SUM(othercol) AS psum
        FROM    othertable
        GROUP BY
                yetothercol
        ) s
ON      yetmycol = yetothercol
SET     mycol = psum

, or in a MERGE statement (works in Oracle and SQL Server 2008):

MERGE
INTO    mycol
USING   (
        SELECT  yetothercol, SUM(othercol) AS psum
        FROM    othertable
        GROUP BY
                yetothercol
        ) s
ON      (yetmycol = yetothercol)
WHEN MATCHED THEN
UPDATE
SET     mycol = psum
like image 93
Quassnoi Avatar answered Apr 27 '26 21:04

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!