MySQL嵌套优化

时间:2013-04-25 10:11:41

标签: mysql

我一直试图解决这个问题2个小时,但不能成功

以下是此查询的回复:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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