加入后选择汇总

时间:2014-07-10 11:18:22

标签: mysql inner-join rollup

从UX post

移出

我有2个查询,每个查询都卷起来。


  SELECT DATE(date) AS day, 
         COUNT(IF(name = 'red', 1, NULL)) AS "red",
         COUNT(IF(name = 'blue', 1, NULL)) AS "blue",
         COUNT(IF(name = 'yellow', 1, NULL)) AS "yellow" 
    FROM test1 
GROUP BY day with rollup  

  SELECT DATE(date) AS day, 
         COUNT(*) AS total 
    FROM test2 
GROUP BY day with rollup

加入时,rollup行会被移除,所以我通过使用另一个查询计算rollupunion到结果的末尾来解决它

这里是一个现场演示 [sqlfiddle],关于我这样做的方式(如最佳做法或表现)的任何想法,如果有办法保留{{1}加入后,我不知道。任何指针都赞赏。

更新

我想要的正确结果集是小提琴中的结果。每行包含一天的摘要,从第一个查询项目/颜色数量和第二个查询当天的多个请求。汇总将是每个项目/颜色和请求的分类总和。希望我明确表示:)

1 个答案:

答案 0 :(得分:2)

我认为“汇总”不会被删除。生成的行与join条件不匹配。你可以试试这个:

select t1.*, t2.total
from (SELECT date(date) as day, count(IF(name = 'red', 1, NULL)) AS "red",
             sum(name = 'blue') AS blue,
             sum(name = 'yellow') AS yellow
      FROM test1
      group by day with rollup 
     ) t1 join 
     (select date(date) as day, count(*) as total
      from test2
      group by day with rollup
     ) t2
     on t1.day = t2.day or t1.day is null and t2.day is null;