在使用连接时我不是很好 - 所以我有一个表,我在计算满足特定条件的记录数,并按周返回这些计数。问题是,我需要那些零计数的周......我试图让它与左连接一起工作,但我正在努力...任何帮助赞赏:(邮票是一个日期时间字段)< / p>
查询:
SELECT week(stamp), count(*) AS mycount, YEAR(stamp) as theyear
FROM merges
WHERE completed = 1
AND stamp BETWEEN '2017/4/1 00:00:00' AND '2017/6/1 00:00:00' GROUP BY week(stamp)
返回:
week(stamp) | mycount | theyear
15 | 21 |2017
17 | 10 |2017
18 | 62 |2017
19 | 13 |2017
20 | 76 |2017
21 | 22 |2017
第16周缺席?我需要将此结果包含在上面,例如:
16 | 0 |2017
我感谢任何帮助 - 我知道这不是太难,但是当我读其他帖子的时候,我正试图理解如何做到这一点....
答案 0 :(得分:0)
select weekValue, yearValue, coalesce(mycount,0)
from
( SELECT distinct week(@startDate := @startDate + Interval 1 day) as weekValue,
year(@startDate := @startDate + Interval 1 day) as yearValue
FROM
(select 0 union all select 1 union all select 3 union all select 4
union all select 5 union all select 6 union all select 6 union all select 7
union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 3
union all select 4 union all select 5 union all select 6
union all select 6 union all select 7 union all select 8 union all select 9) t2,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t3,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t4,
(SELECT @startDate := '2017-03-31 00:00:00' ) as g
where
@startDate < '2017-06-01 00:00:00' ) as generateWeekYear left join
(SELECT week(stamp) as theweek, count(*) AS mycount, YEAR(stamp) as theyear
FROM merges
WHERE completed = 1
AND stamp BETWEEN '2017/4/1 00:00:00' AND '2017/6/1 00:00:00' GROUP BY week(stamp) ) as actualQuery
on generateWeekYear.weekValue = actualQuery.theweek
and generateWeekYear.yearValue = actualQuery.theyear
让我解释一下上面的问题,
子查询generateWeekYear =这用于根据两个输入生成不同的周和年 让我们说startDate和endDate。 startDate应该比实际startDate少1天。因为如果你不这样做 减去1天然后有可能松开一周。
现在您需要显示所有周和年。
现在你认为generateWeekYear会有更多的时间来执行,但事实并非如此。您可以 检查这个generate an integer sequence in MySQL。
之后,您只需将上表与上表联系起来即可获得所需结果。