mysql按日期查询数据_mysql按日期查询数据

问题:mysql按日期查询一个月内的数据,查询返回时结果集中只显示有数据的结果

需求:查询结果中假如当天没有数据,自动填零并输出

事件描述:

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;

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明mysql按日期查询数据!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值