问题:mysql按日期查询一个月内的数据,查询返回时结果集中只显示有数据的结果
需求:查询结果中假如当天没有数据,自动填零并输出
事件描述:
sql语句:
需求:查询结果中假如当天没有数据,自动填零并输出
事件描述:
sql语句:
select DATE_FORMAT(date_added,"%m.%d") as day,count(product_id) as total from ht_product where DATE_FORMAT(date_added,"%m")=7 group by day;
返回结果:
day total
07.23 1
07.25 4
07.26 2
07.27 1
期望结果:
day total
07.01 0
07.02 0
…
07.22 0
07.23 1
07.24 0
07.25 4
07.26 2
07.27 1
07.28 0
…
07.31 0
解决方案
40
create table ht_product( date_added datetime, product_id int); insert ht_product values ("2016-7-4", 11), ("2016-7-4", 33), ("2016-7-7", 11), ("2016-7-10", 33); select _dt.day, coalesce(data.total, 0) as total from( select date_format(_id.date,"%m.%d") as day from( select date_add("2016-07-01", interval @i day) as date, @i:=@i+1 as id from information_schema.columns a, (select @i:=0) _a order by id limit 31 ) _id where DATE_FORMAT(_id.date,"%m")=7 ) _dt left join( select DATE_FORMAT(date_added,"%m.%d") as day,count(product_id) as total from ht_product where DATE_FORMAT(date_added,"%m")=7 group by day ) data on data.day = _dt.day order by day ; drop table ht_product;