更新列Group by的SUM

时间:2011-08-11 22:27:06

标签: mysql group-by sum

UPDATE table_name SET col3 = SUM(col2) GROUP BY col1

发出错误:

  

您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在'GROUP BY col1'

附近使用正确的语法

如何解决这个问题?

Col1  | col2  |   col3
Water |   22  |
water |   3   |
water |   5   |
Air   |  10   |
Earth |  3    |
Air   |  5    | 

I want in col3 the results as follows

Col1  | col2  |   col3
Water |   22  |   30
water |   3   |   30
water |   5   |   30
Air   |  10   |   15
Earth |  3    |   3
Air   |  5    |   5

3 个答案:

答案 0 :(得分:3)

子查询

UPDATE table_name SET col3 = (SELECT SUM(x.col2) FROM (SELECT * FROM table_name) AS x WHERE x.col1 =  table_name.col1)

这将为更新的每一行执行子查询,获取与col1匹配的每一行的col2总和

问题是,你为什么要这样做?如果需要,你总是可以使用SUM来获取这些信息。

答案 1 :(得分:1)

您可以将查询编写为:

UPDATE test_table t1
INNER JOIN (
                SELECT col1, SUM(col2) AS sum_col2 FROM test_table GROUP BY col1
           ) t2
ON  t1.col1  =  t2.col1
SET t1.col3  =  t2.sum_col2;

Working demo

答案 2 :(得分:-1)

UPDATE table_name SET col3 = (Select SUM(col2) From table_name where col1=col1)