MySQL achieve grouped by day statistics, to provide a complete list of dates, no data is automatically fill 0

Business needs
to be newly added to the system, statistical functions, requirements are specified date range statistic data grouped by day, and to be able to view the amount of data that period of time each day.

Solutions
directly on the data table date field group by statistics, no data found that if one day, the date is not present, which is not in line with business needs. Baidu found that some programs are basically two: First, create a new list of dates, the date of the next 10 years into them, and then talk to statistics as join queries; the second is the application code more consecutive dates union queries in SQL logic. They are more complicated.
Reference Oracle's "select level from dual connect by level <31" the realization of ideas:
1, first with a query the list of dates specified date range out out

SELECT 
    @cdate: = date_add(@cdate, interval - 1 day) as date_str, 0 as date_count
FROM(SELECT @cdate: = date_add(CURDATE(), interval + 1 day) from t_table1) t1

2, business statistics inquiry also above date and the number of inquiries to date statistics set the alias

SELECT
    FROM_UNIXTIME(m.sdate, '%Y-%m-%d') as date_str, count( * ) as date_count
from t_table1 as m
group by FROM_UNIXTIME(m.sdate, '%Y-%m-%d')

3, taken together the two queries connected with the left, not the number of dates to fill 0

SELECT t1.date_str, COALESCE(t2.date_total_count, 0) as date_total_count
FROM(
    SELECT @cdate: = date_add(@cdate, interval - 1 day) as date_str FROM(SELECT @cdate: = date_add(CURDATE(), interval + 1 day) from t_table1) tmp1 WHERE @cdate > '2018 - 12 - 01'
) t1
LEFT JOIN(
    SELECT FROM_UNIXTIME(m.sdate, '%Y-%m-%d') as date_str, count(*) as date_total_count FROM t_table1 as m WHERE m.sdate between XXXX and XXXXX GROUP BY FROM_UNIXTIME(m.sdate, '%Y-%m-%d')
) t2
on t1.date_str = t2.date_str

Results shown below:

 

Guess you like

Origin www.cnblogs.com/rinack/p/11105779.html