This question already has an answer here:
I have this query and I want to fill missing dates with some values (zero for example...)
SELECT date, SUM(val1) as sum_val
FROM table1
WHERE date BETWEEN '2016-03-04' AND '2016-03-10'
GROUP BY date
Here is result:
|--------------------------
|date, sum_val
|--------------------------
|2016-03-04, 21568
|--------------------------
|2016-03-05, 14789
|--------------------------
|2016-03-08, 20568
|--------------------------
|2016-03-10, 5841
|--------------------------
How can I populate missing dates with zero values? Does anyone has an idea?
I need this data for chart preview.
You can try this PHP loop:
strtotime("+1 day", strtotime($date1))
will increment by 1 day the current value of$date1
until it is equal to$date2
.When a date does not have a value it will be zero, and if the date exist, it will get the sum according to MySQL result.
Use below code its similar to your query and surely work and helful to you.
In general, you can generate a series of N integers in MySQL using:
Note that the table that you join on (someTable) must have at least N rows. The -1 above is to make it base-zero... remove it and you'll get 1,2,3 for N=3.
You can feed those integers into the DATE_ADD function to turn it into a series of dates. To make it easier to follow, let's use some user variables for the dates.
That will return rows for those days and every day between them. Now it's just a matter of joining against your table... I haven't tried it since I don't have your db structure, but something like the following should work: