计算今年每个月的行数

时间:2017-07-23 17:23:27

标签: mysql outer-join

现在我的问题很简单我在mysql中有很多行,例如

name    created_at
A       2017-05-1
B       2017-05-1
C       2017-06-2

现在我已经运行了这个查询

SELECT MONTH(created_at) , COUNT(created_at) 
FROM invoices
WHERE created_at >= NOW() - INTERVAL 1 YEAR
GROUP BY MONTH(created_at)

这给了我正确的结果

5    2
6    1

但我也想要前几个月的统计数据

1    0
2    0
3    0
4    0
5    2
6    1

如何修改我的查询?

1 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个包含1到12个月的表格:

CREATE TABLE months (month INT PRIMARY KEY);
INSERT INTO months (month) 
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12);

然后使用OUTER JOIN将其加入到您的结果中:

SELECT m.month, COALESCE(i.count, 0) AS count
FROM months AS m
LEFT OUTER JOIN (
    SELECT MONTH(created_at) AS month, COUNT(created_at) AS count
    FROM invoices
    WHERE created_at >= NOW() - INTERVAL 1 YEAR
    GROUP BY MONTH(created_at)
) AS i ON m.month = i.month