Faizan Ahmad :
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
----------------------------------
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?
GMB :
For just 7 days, one method is to use a derived table of numbers, and left join
it with the original table:
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
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