I have a table looks like:
id | date | count
-----------------------
1 | 2016-07-13 | 2
2 | 2016-07-13 | 3
3 | 2016-07-13 | 1
4 | 2016-07-15 | 12
5 | 2016-07-15 | 1
6 | 2016-07-15 | 4
This is my query
$test_query = $wpdb->get_results("
SELECT
SUM(count) AS count,
date
FROM
".$wpdb->prefix."statistics
WHERE
date BETWEEN DATE_SUB('2016-07-15', INTERVAL 2 DAY) AND '2016-07-15'
GROUP BY DATE(date)
");
I run the query to get the results
2016-07-13 | 6
2016-07-15 | 17
This working good, only I have a interval for 3 days and the results from the date 2016-07-14 is not showing up. I use a chart where the value needs to be empty or 0.
Is there a way that 2016-07-14 value is 0?
2016-07-13 | 6
2016-07-14 | 0
2016-07-15 | 17
I have found a solution. I've got a startdate and a enddate. With a for loop, I get all the dates between them. Then I compare them with the date in the database.
Thank you all for the reactions!
You can try the following query:
SELECT
v.selected_date,
COALESCE(YT.count,0) AS count
FROM
(select adddate(DATE_SUB('2016-07-15', INTERVAL 2 DAY),t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
LEFT JOIN
(
SELECT
SUM(count) AS count,
date
FROM
statistics #Your table name
WHERE
date BETWEEN DATE_SUB('2016-07-15', INTERVAL 2 DAY) AND '2016-07-15'
GROUP BY DATE(date)
) AS YT
ON YT.date = v.selected_date
WHERE v.selected_date BETWEEN DATE_SUB('2016-07-15', INTERVAL 2 DAY) AND '2016-07-15' ;
Note:
The highlighted parts will vary according to your given date range.
In the first highlighted part put the start date of your date range.
In the second and third highlighted part put your whole date range like you did in your given query.