UPDATE with SELECT from another, but with a SUM field (someField)

Basically, I have something like this:

UPDATE
    Table
SET
    Table.col1 = other_table.col1,
FROM
    Table
INNER JOIN
    other_table
ON
    Table.id = other_table.id

The problem is that I would like to update col1by selecting select:

SELECT SUM(col1) FROM other_table WHERE Table.id = other_table.id AND period > 2011

Edit

Correct answer:

UPDATE bestall  
INNER JOIN (SELECT bestid,SUM(view) as v,SUM(rawView) as rv 
                           FROM beststat 
                           WHERE period > 2011 GROUP BY bestid) as t1 
ON bestall.bestid = t1.bestid
SET view = t1.v, rawview = t1.rv
+3
source share
1 answer

You cannot use aggregates directly in a proposal set. One way is a subquery:

update  your_table as yt
left join 
        (
        select  id
        ,       count(*) as cnt
        from    other_table
        where   period < 4
        group by
                id       
        ) as ot
on      yt.id = ot.id 
set     col1 = coalesce(ot.cnt,0)

Example in SQL Fiddle.

+3
source

All Articles