1

我正在寻找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

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

谢谢!

4

2 回答 2

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'
于 2013-03-30T07:27:24.983 回答
0

做这个:

Declare @avg decimal(10,2)
Set @avg=(SELECT AVG(balance) FROM mc25778 WHERE status = 0)
UPDATE mc25778 set balance=@avg WHERE username="Average"
于 2013-03-30T07:46:49.760 回答