MySQL:按两列分组包括零项目计数

时间:2018-02-21 21:35:37

标签: mysql

我想计算" ID"的总数。按"日期"分组和"键入",如果一个" date" "类型"不存在打印0。

我有这张桌子:

id  type    date
1    0      2015-11-12
2    1      2015-11-12
3    0      2015-11-12
4    0      2016-10-07
5    0      2016-10-07
6    0      2016-12-02
7    1      2017-03-08
8    0      2018-02-01

我希望看到的例子:

 COUNT(*)|type| date
   2     |  0 | 2015-11-12
   1     |  1 | 2015-11-12
   2     |  0 | 2016-10-07
   0     |  1 | 2016-10-07
   1     |  0 | 2016-12-02
   0     |  1 | 2016-12-02
   0     |  0 | 2017-03-08
   1     |  1 | 2017-03-08
   1     |  0 | 2018-02-01
   0     |  1 | 2018-02-01

我在这里发布了代码:http://sqlfiddle.com/#!9/b15329

请你的帮助。

2 个答案:

答案 0 :(得分:0)

select IFNULL(COUNT(*), 0) AS count,type,date from test group by date,type

答案 1 :(得分:0)

这应该做的工作:

SELECT IFNULL(C.count,0) AS count, D.date, T.type FROM
  (SELECT DISTINCT date FROM test) AS D CROSS JOIN
  (SELECT DISTINCT type FROM test) AS T LEFT JOIN
  (SELECT COUNT(*) AS count, date, type FROM test GROUP BY date, type) AS C
      ON C.date = D.date AND C.type = T.type
ORDER BY D.date, T.type

小提琴here