I am trying to write a query that counts the number of records that were created every 7 days,
Using this query i get the number of records created per day,
SELECT 'Closed' AS `Status`, COUNT(*) AS `Count`, `raisedon` AS `Date` FROM table WHERE raisedon >= '2019-01-01' and raisedon < '2019-03-29' AND status = 'Open' AND type = 'A' AND location = 'B' AND locationid = 'C' GROUP BY raisedon
This returns
Closed 1 2019-01-01
Closed 1 2019-01-14
Closed 2 2019-01-16
Closed 1 2019-01-24
Closed 1 2019-01-25
Closed 1 2019-01-30
Closed 1 2019-02-01
Closed 1 2019-02-03
Closed 1 2019-02-28
Closed 1 2019-03-07
Closed 1 2019-03-08
I would like the results to be like
Closed 1 2019-01-01
Closed 1 2019-01-08
Closed 2 2019-01-15
Closed 2 2019-01-22
Closed 3 2019-01-29
Closed 0 2019-02-05
Closed 0 2019-02-12
Closed 0 2019-02-19
Closed 1 2019-02-26
Closed 2 2019-03-05
Is this possible with just a query or will i have to use javascript aswell,
I am using phpmyadmin with mysql
Thanks for any advice
2
Answers
One method uses
datediff()
:If you are not too picky about your edge conditions for where a given week starts, you might just be able to aggregate using
YEARWEEK
:This answer assumes that your data would have at least one data point present for each week. If there could be large gaps, then one solution would be to join with a calendar table. Here is an example of how to do this:
See here for several ways to generate a calendar table like the one used above in the second query.