2013-04-25 92 views
0

我一直在試圖解決現在這個2小時,並不能成功MySQL的嵌套優化

附在下面是該查詢的響應:

SELECT login, SUM(gain) AS weekly_gain 
FROM gt_history 
WHERE is_closed = 1 AND (cmd = 0 OR cmd = 1) 
GROUP BY WEEK(close_time), login 

現在,我想要做的是,要製作一個AVERAGE的所有值,請登錄GROUP BY

想法?

result from first query

+2

爲什麼總結,當你需要平均? – 2013-04-25 10:17:26

+0

我需要總結每週的日子,然後每週平均 – user502967 2013-04-25 10:35:13

回答

1

只需使用查詢你的子查詢。

SELECT login, AVG(weekly_gain) FROM 
    (SELECT login, SUM(gain) AS weekly_gain 
    FROM gt_history 
    WHERE is_closed = 1 AND (cmd = 0 OR cmd = 1) 
    GROUP BY WEEK(close_time), login) 
GROUP BY login 
+0

非常感謝你! :) – user502967 2013-04-25 10:53:08

1
SELECT 
    login, 
    AVG(weekly_gain) AS weekly_gain 
FROM (SELECT 
    login, 
    SUM(gain) AS weekly_gain 
     FROM gt_history 
     WHERE is_closed = 1 
     AND (cmd = 0 
     OR cmd = 1) 
     GROUP BY WEEK(close_time), login) As l 
+0

否:(你的查詢返回一般平均值而不是每週總和的平均值:) – user502967 2013-04-25 10:28:43