使用平均列更新记录

时间:2013-03-30 07:24:24

标签: mysql sql sql-update

我希望找到status = 0的列的平均值,并将其更新到该表中的另一条记录中。 这是我试图使用的查询。

UPDATE mc25778 set balance=(AVG(balance WHERE status=0)) WHERE username="Average"

尝试执行此任务时出现此错误:

   Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE status=0)) WHERE username="Average"' at line 1

我有什么想法可以解决这个问题吗?

谢谢!

2 个答案:

答案 0 :(得分:6)

您可以使用子查询加入表,该子查询分别计算每个用户名的平均值

UPDATE  mc25778 a
        INNER JOIN 
        (
            SELECT  username, AVG(balance) avg_bal
            FROM    mc25778 
            WHERE   status = 0
            GROUP   BY username
        ) b ON a.username = b.username
SET     a.balance = b.avg_bal
WHERE   a.username = 'Average'

更新1

您似乎想要计算所有status = 0条记录的总平均值,其结果将在Average

的记录中更新
UPDATE  mc25778 a
        CROSS JOIN
        (
            SELECT  AVG(balance) avg_bal 
            FROM    mc25778 
            WHERE   status = 0
        )  b
SET     a.balance = b.avg_bal
WHERE   a.username = 'Average'

答案 1 :(得分:0)

这样做:

Declare @avg decimal(10,2)
Set @avg=(SELECT AVG(balance) FROM mc25778 WHERE status = 0)
UPDATE mc25778 set balance=@avg WHERE username="Average"