MySQL: select all dates between date range and get date date data

There is a table that has the data as such:

-----------------------
|   id   |    date    |
-----------------------
|   1    | 2016-07-11 |
|   2    | 2016-07-11 |
|   3    | 2016-07-15 |
|   4    | 2016-07-15 |
|   5    | 2016-07-15 |
|   6    | 2016-07-16 |
|   7    | 2016-07-19 |
|   8    | 2016-07-20 |
-----------------------

      

I want to get the date range (all dates) and the number of ids for each date, returning 0 if there are no records.

If you run dates between 2016-07-10 to 2016-07-20, the result should look like this:

--------------------------
|    date    | count(id) |
--------------------------
| 2016-07-10 |     0     |
| 2016-07-11 |     2     |
| 2016-07-12 |     0     |
| 2016-07-13 |     0     |
| 2016-07-14 |     0     |
| 2016-07-15 |     3     |
| 2016-07-16 |     1     |
| 2016-07-17 |     0     |
| 2016-07-18 |     0     |
| 2016-07-19 |     1     |
| 2016-07-20 |     1     |
--------------------------

      

I found solutions to get a range of dates , but couldn't figure out how to get it to count the ids that exist for those dates in the table.

Thank!

+2


source to share


3 answers


I figured it out by modifying the query given in the solution to get all dates.

The following query returns all dates and the number of ids if records exist:



select d.date, count(v.id) from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) 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) d
left join visitors v on d.date = v.date
where d.date between '2016-06-01' and '2016-06-30'
group by d.date
order by d.date

      

Provided to get @ mark-bannister date range and simple query join matching the results and sorting gets the solution.

+4


source


Try this: Basically, you need a group to help you get the desired result. In addition, if necessary, you must specify a condition with a range



SELECT date ,count(date) from datetable group by date;

      

0


source


Just,

WHERE `date` BETWEEN '2016-07-10' AND '2016-07-20'

      

-1


source







All Articles