这是表格测试的数据:
time | type
2017-11-01 | a
2017-11-01 | a
2017-11-01 | a
2017-11-01 | b
2017-11-02 | a
2017-11-02 | b
2017-11-02 | b
2017-11-02 | b
2017-11-02 | c
2017-11-03 | a
2017-11-03 | a
如何获得结果:
time | type | count(*)
2017-11-01 | a | 3
2017-11-01 | b | 1
2017-11-01 | c | 0
2017-11-02 | a | 1
2017-11-02 | b | 3
2017-11-02 | c | 1
2017-11-03 | a | 2
2017-11-03 | b | 0
2017-11-03 | c | 0
我尝试使用group by和ifnull,但它无效。我无法从数据中得到0。也许'加入'可以工作,但如何编辑SQL?
答案 0 :(得分:2)
您可以将所有不同类型交叉连接到所有不同的日期(笛卡尔积)
MariaDB [sandbox]> select distinct type,t1.dt from t
-> cross join (select distinct dt from t) t1;
+------+------------+
| type | dt |
+------+------------+
| a | 2017-11-01 |
| b | 2017-11-01 |
| c | 2017-11-01 |
| a | 2017-11-02 |
| b | 2017-11-02 |
| c | 2017-11-02 |
| a | 2017-11-03 |
| b | 2017-11-03 |
| c | 2017-11-03 |
+------+------------+
9 rows in set (0.00 sec)
然后离开加入
MariaDB [sandbox]> select s.type,s.dt,ifnull(u.obs,0) obs
-> from
-> (
-> select distinct type,t1.dt from t
-> cross join (select distinct dt from t) t1
-> ) s
-> left join
-> (select type,dt, count(*) obs from t group by type,dt) u on u.type = s.type and u.dt = s.dt ;
+------+------------+-----+
| type | dt | obs |
+------+------------+-----+
| a | 2017-11-01 | 3 |
| b | 2017-11-01 | 1 |
| c | 2017-11-01 | 0 |
| a | 2017-11-02 | 1 |
| b | 2017-11-02 | 3 |
| c | 2017-11-02 | 1 |
| a | 2017-11-03 | 2 |
| b | 2017-11-03 | 0 |
| c | 2017-11-03 | 0 |
+------+------------+-----+
9 rows in set (0.00 sec)
请注意,这仅适用于您对某些活动的日期感兴趣的情况 - 如果不考虑构建压缩表并在子查询中使用