我需要获取一个列表,其中包含过去 6 个月中每月的人数, 如何强制查询提供 count = 0 的月份?像这样:
table A
-----------------------------
id | name | created |
-----------------------------
1 | mark |'2014-10-01'|
2 | peter |'2014-10-02'|
3 | Roger |'2014-10-03'|
4 | John |'2014-09-02'|
5 | moyes |'2014-09-03'|
6 | david |'2014-08-04'|
我需要得到的结果:
----------------------------
MONTHS | YEARS | TOTAL |
----------------------------
January | 2015 | 0 |
December| 2014 | 0 |
November| 2014 | 0 |
October | 2014 | 3 |
September| 2014 | 2 |
August | 2014 | 1 |
到目前为止我尝试过的查询: http://sqlfiddle.com/#!2/ef54ce/6
最佳答案
也许,您必须提供包含初始数据报告的虚拟表。 然后,与实际数据结合。为了避免重复数据,您需要使用聚合
SELECT
m, y, MAX(v) v
FROM
(
SELECT
DATE_FORMAT('2014-01-01', '%M') as m,
DATE_FORMAT('2014-01-01', '%Y') as y,
0 as v
UNION
SELECT
DATE_FORMAT('2014-02-01', '%M') as m,
DATE_FORMAT('2014-02-01', '%Y') as y,
0 as v
UNION
.... until December ...
UNION
SELECT
DATE_FORMAT(created, '%M') as m,
DATE_FORMAT(created, '%Y') as y,
COUNT(1) as v
FROM your_table
GROUP BY DATE_FORMAT(created, '%Y-%M')
) t
GROUP BY y, m
... adjust result ...
关于Mysql 查询获取最近 6 个月的计数,包括计数 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213409/