Quantcast
Channel: Answers for "how to store value of avg(col1) into col2 in same table"
Viewing all articles
Browse latest Browse all 4

Answer by Matt Whitfield

$
0
0

That doesn't make any sense - why would you want to store the average value of multiple rows into a single row, or repeat the value multiple times?

Senseless as it is, the code would be:

UPDATE table
   SET col2 = (SELECT AVG(col1) FROM table)

This would put the average of col1 into col2 for all rows.

Edit -> After your edit, to do it for a sub-set, you want:

UPDATE tablename
   SET col2 = (SELECT AVG(col1)
                 FROM tablename
                WHERE restaurantName = tmain.tablename)
  FROM tablename tMain

It still doesn't make a great deal of sense to do this, however. It would be much better to extract the average when you need it, instead of forcing every row to update each time any row updates. Something like:

SELECT restaurantName, col1, AVG(col1) OVER (PARTITION BY restaurantName)
  FROM table

Viewing all articles
Browse latest Browse all 4

Trending Articles