mysql-按列分组时选择零计数

前端之家收集整理的这篇文章主要介绍了mysql-按列分组时选择零计数 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个工作表,正在尝试获取不同时间范围内的工作数.我当前的查询如下所示:

SELECT COUNT(*) AS 'count',WEEK(j.created_at) AS 'week',MONTH(j.created_at) AS 'month',YEAR(j.created_at) AS 'year',DATE_FORMAT(j.created_at,'%y') AS 'short_year'
FROM jobs j WHERE j.state <> 'draft' 
            AND created_at > '2010-06-21'
            AND created_at < '2010-08-01'
GROUP BY WEEK(j.created_at)
ORDER BY WEEK(j.created_at)

要更改时间范围,我只需将GROUP BY从WEEK更改为MONTH,就可以按月而不是按周进行计数.

问题是我有0个工作的几周没有空行.我从上面的查询中得到的结果是:

count week  month  year short_year
    3   25      6  2010         10
    2   26      6  2010         10
    2   27      7  2010         10 
    1   28      7  2010         10
    3   30      7  2010         10

您会注意到第29周没有数据,该数据应该是带有count(0)的行.有什么办法可以使那0计数行,同时保持在WEEK和MONTH之间更改分组的灵活性?

最佳答案
创建一个包含每个日期和该日期的外部联接的辅助日历表(如果created_at具有时间分量,则下面可能需要调整)

SELECT COUNT(*) AS 'count',WEEK(c.date) AS 'week',MONTH(c.date) AS 'month',YEAR(c.date) AS 'year',DATE_FORMAT(c.date,'%y') AS 'short_year'
FROM calendar c
LEFT OUTER JOIN jobs j ON j.created_at = c.date
            AND j.state <> 'draft' 
WHERE c.date > '2010-06-21'
            AND c.date < '2010-08-01'
GROUP BY WEEK(c.date)
ORDER BY WEEK(c.date)

猜你在找的MySQL相关文章