【问题标题】:Group by month and return months where result is 0 filtering by year [duplicate]按月分组并返回结果为0的月份按年份过滤[重复]
【发布时间】:2018-08-16 19:26:50
【问题描述】:

我正在尝试按月对给定表的结果进行分组并返回没有值的地方,我创建了另一个表,但我无法按年份过滤条目(例如,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... 子句是导致这种行为的原因,我怎样才能让我的查询像我想要的那样工作?

【问题讨论】:

  • 请告诉我们您的months 表是什么样的。请edit您的问题。
  • 月份表基本上是查询返回的,只有 ID 和它的名称
  • 考虑处理应用代码中数据显示的问题
  • YEAR(created_at) = 2018 移动到ON 子句中。另外,您可以将COUNT(MONTH(created_at)) 更改为COUNT(created_at)
  • @Balmbar 成功了,真棒!

标签: mysql date aggregate


【解决方案1】:

尝试使用左连接而不是右连接

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

【讨论】:

  • 是的。但是从months 表和LEFT JOIN entries 表开始。该模式确保每个月都有一行,即使 entries 有几个月没有匹配的行。
  • 很好 @O.Jones +1 :) 我更新了我的代码
  • 仍然得到相同的结果,它没有返回应该是 0 计数的列中的值
  • 您是否尝试过我刚刚根据@O.Jones 所做的更新代码编辑?注意表格从条目切换到月份
  • 更新了我的问题,“created_at”列属于条目
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多