我需要获得一个列表,其中包含过去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
答案 0 :(得分:0)
也许,您必须提供包含初始数据报告的虚拟表。 然后,与实际数据结合。为避免重复数据,您需要使用聚合
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 ...