2013-03-30 39 views
1

我正在尋找狀態= 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 

任何想法如何,我可以排序了這一點?

謝謝!

回答

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' 
+0

HM ...其實它說受影響的行:0!我正在尋找錯誤的地區哈哈。所以它不起作用:/ –

+0

你能給你想要的結果樣本記錄嗎? ':)' –

+0

http://imgur.com/nMAvyev好的,所以在這裏它顯示了表中的記錄,我正在尋找更新'平均'用戶名一到所有的平衡狀態= 0,對不起,混亂! –

0

這樣做:

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