我有一张工作表,我正在尝试计算不同时间段的工作。我当前的查询如下所示:
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
之间更改分组的灵活性?
答案 0 :(得分:3)
创建一个辅助日历表,其中包含每个日期和外部联接(如果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)