获取今年每个月的行数
Getting count of rows from every month of this year
现在我的问题很简单,例如 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
如何修改我的查询?
最简单的方法是创建一个 table 月 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
现在我的问题很简单,例如 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
如何修改我的查询?
最简单的方法是创建一个 table 月 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