mysql 2组使用groupby rollup求和

发布于 2024-11-05 07:21:43 字数 423 浏览 0 评论 0原文

我有一个查询

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

查询工作正常。但我还需要找到第二个总和(小时),其中按顺序分组发生了变化。

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

(实际的where条件要长得多。)

是否有可能同时获得总和单个查询自where条件几乎相同?

I have a query

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

The query works fine. But I also need to find a second sum(hours) where the group by order is changed.

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

(The actual where condition is much longer.)

Is it possible to get both the sum in a single query since the where condition almost the same?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤单情人 2024-11-12 07:21:43
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*/

根据您的需求,您应该只需要一个或两个带有汇总的

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*/

Depending on your needs, you should only need one with rollup, or two.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文