按月分组并返回月份,其中按年份过滤结果为0

时间:2018-08-16 19:26:51

标签: mysql date aggregate

我试图按月对给定表的结果进行分组,并在没有值的地方返回,我创建了另一个表,但是无法按年份过滤条目(例如where YEAR(created) = 2018) ,但内部查询未返回预期的月份。

我有这个查询。

SELECT 
    months.name as m, 
    count(MONTH(created_at)) as total 
from entries 
RIGHT JOIN months 
    ON MONTH(created_at) = months.id 
where YEAR(created_at) = 2018 
GROUP BY months.id

查询的结果是这样:

+----+------------------+---------------------------+
| id | month            | total                     |
+----+------------------+---------------------------+
|  1 | january          | 27                        |
|  3 | march            | 3                         |
|  5 | may              | 2                         |
+----+------------------+---------------------------+

我想实现以下目标:

+----+------------------+-------+
| id | month            | total |
+----+------------------+-------+
|  1 | january          | 27    |
|  2 | february         | 0     |
|  3 | march            | 3     |
|  4 | april            | 0     |
|  5 | may              | 2     |
|  6 | june             | 0     |
|  7 | july             | 0     |
|  8 | august           | 0     |
|  9 | september        | 0     |
| 10 | october          | 0     |
| 11 | november         | 0     |
| 12 | december         | 0     |
+----+------------------+-------+

我假设我的where year...子句是导致这种行为的那个子句,如何使我的查询像我想要实现的那样工作?

1 个答案:

答案 0 :(得分:0)

尝试执行左联接而不是右联接

SELECT months.name as m, 
   IFNULL(Count(created_at), 0) as total 
  from months
  LEFT JOIN ENTRIES ON months.id = MONTH(created_at)
  where YEAR(created_at) = 2018 
  GROUP BY months.id