[英]Get report of last week of all days including days with 0 count
I am trying to get a report of last week entries/tickets and show 0 if that day there was none entries and then show it in google line chart for a project.MySQL table look like this我正在尝试获取上周条目/门票的报告,如果当天没有条目,则显示 0,然后在项目的谷歌折线图中显示它。MySQL 表如下所示
----------------------------------
id body timeSent
----------------------------------
1 someText 2020-02-29 15:48:18
2 someText 2020-03-02 11:32:07
3 someText 2020-03-02 11:32:07
4 someText 2020-03-04 12:11:13
5 someText 2020-03-05 09:32:09
----------------------------------
I wrote query like this我写了这样的查询
SELECT count(*) as count_tickets,
substr(timeSent,1,10) AS datetime
FROM tableName
WHERE substr(timeSent,1,10) >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY substr(timeSent,1,10)
ORDER BY timeSent
Output look like this输出看起来像这样
----------------------------------
count_tickets dateTime
----------------------------------
1 2020-02-29
2 2020-03-02
1 2020-03-04
1 2020-03-05
----------------------------------
What my required output is我需要的输出是什么
----------------------------------
count_tickets dateTime
----------------------------------
1 2020-02-29
0 2020-03-01
2 2020-03-02
0 2020-03-03
1 2020-03-04
1 2020-03-05
0 2020-03-06
----------------------------------
How can I achieve this?我怎样才能做到这一点?
For just 7 days, one method is to use a derived table of numbers, and left join
it with the original table:仅仅7天,一种方法是使用导出的数字表,并将其与原始表进行
left join
:
select
count(t.timesent) as count_tickets,
current_date - interval x.n day as datetime
from (
select 0 n union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6
) x
left join tablename t
on t.timesent >= current_date - interval x.n day
and t.timesent < current_date - interval (x.n - 1) day
group by x.n
order by x.n desc
Demo on DB Fiddle : DB Fiddle 上的演示:
count_tickets | datetime ------------: | :--------- 1 | 2020-02-29 0 | 2020-03-01 2 | 2020-03-02 0 | 2020-03-03 1 | 2020-03-04 1 | 2020-03-05 0 | 2020-03-06
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.