我不太擅长使用联接 - 所以我有一个表,我在其中计算满足特定条件的记录数,并按周返回这些计数。问题是,我也需要计数为零的周......我试图让它与左连接一起工作,但我正在努力......任何帮助表示赞赏:(邮票是一个日期时间字段)
查询:
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
我感谢任何帮助 - 我知道这并不太难,但我在阅读其他帖子时绞尽脑汁试图了解如何做到这一点......
最佳答案
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 =这用于根据两个输入生成不同的周和年 让我们说开始日期和结束日期。开始日期应比实际开始日期少 1 天。因为如果你不这样做 减去 1 天,则可能有机会减掉 1 周。
现在您拥有需要显示的所有周和年。
现在您认为generateWeekYear 的执行时间会更长,但事实并非如此。你可以 检查这个generate an integer sequence in MySQL 。
之后,您只需将您的表格与上面的表格连接起来,就可以获得您所需的结果。
关于MySQL 查询 - 转换为左连接以显示零结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44286053/