mysql 2使用groupby汇总的总和

时间:2011-05-06 09:20:10

标签: mysql group-by

我有一个查询

select user_id,sum(hours),date, task_id from table where used_id = 'x' and date >='' and date<= '' group by user_id, date, task_id with roll up

查询工作正常。但是我还需要找到第二个总和(小时),其中按顺序更改组。

select user_id,sum(hours),date, task_id from table where used_id = 'x' group by user_id,task_id

(实际情况更长。)

是否有可能在单个查询中获得两个总和,因为where条件几乎相同?

1 个答案:

答案 0 :(得分:0)

SELECT * FROM (
  SELECT 1 AS list_id  
    , user_id
    , sum(hours) AS total_hours
    , `date`
    , task_id 
  FROM table WHERE used_id = 'x' AND `date` BETWEEN @thisdate AND @thatdate 
  GROUP BY user_id, `date`, task_id /*WITH ROLLUP*/
UNION ALL
  SELECT 2 AS list_id 
    , user_id
    , sum(hours) AS total_hours
    , `date`
    , task_id 
  FROM table 
  WHERE used_id = 'x' 
  GROUP BY user_id,task_id WITH ROLLUP ) q
/*ORDER BY q.list_id, q.user_id, q.`date`, q.task_id*/

根据您的需要,您只需要一个with rollup或两个。