views:

184

answers:

3

I'm trying to set the value in one table to the sum of the values in another table. Something along these lines:

UPDATE table1
SET field1 = SUM(table2.field2)
FROM table1
INNER JOIN table2 ON table1.field3 = table2.field3
GROUP BY table1.field3

Of course, as this stands, it won't work - SET doesn't support SUM and it doesn't support GROUP BY.

I should know this, but my mind's drawing a blank. What am I doing wrong?

+3  A: 

Use:

UPDATE table1
   SET field1 = (SELECT SUM(t2.field2) 
                   FROM TABLE2 t2 
                  WHERE t2.field3 = field3)
OMG Ponies
I put the three queries side-by-side and ran an execution plan. This answer had a cost of 44%.
Margaret
+3  A: 
UPDATE t1
SET t1.field1 = t2.field2Sum
FROM table1 t1
INNER JOIN (select field3, sum(field2) as field2Sum
   from table2
  group by field3) as t2
on t2.field3 = t1.field3  
JBrooks
I put the three queries side-by-side and ran an execution plan. This answer had a cost of 5%.
Margaret
+1: Thanks Margaret for the info
OMG Ponies
+2  A: 

Or you could use a mix of JBrooks and OMG Ponies answers:

UPDATE table1
   SET field1 = (SELECT SUM(field2)
                   FROM table2 AS t2
                  WHERE t2.field3 = t1.field3)
  FROM table1 AS t1
Paulo Santos
I put the three queries side-by-side and ran an execution plan. This answer had a cost of 51%.
Margaret
Okie dokie! And thanks for the feedback. I'll add it to my toolbox. :-)
Paulo Santos
+1: Was waiting to see what the cost was :)
OMG Ponies