mysql 补全缺少日期_【MYSQL总结】时间范围内数据统计,缺失日期数据为0补全

问题背景

不少系统都有这样的程序流程,以下:前端

前端页面选择时间->后端接收到日期范围数据如(startDate=20190303,endDate=20190401)->查询MYSQLsql

->后端返回数据到前端->前端加载数据渲染曲线后端

可是有时候由于业务自己或者系统异常等缘由会致使某些日期无数据,如上假设20190303天无数,那么前端渲染曲线就会缺失某个点,容易误导用户。code

方案解决

后端获取到日期范围数据(startDate=20190303,endDate=20190401),先生成该范围连续无断点的时间数据.table

如class

select * from(

select  '20190303' time_str

UNION ALL

select  '20190304' time_str

...

UNION ALL

select  '20190401' time_str ) a

把该数据命名为a表。渲染

而后把a表left join  到 select time_str,count(*) num from table group by time_str的统计数据。select

join后 num 结果若是为NULL的话,咱们把它设置为0,如语句case when  num is null then 0 else num end 。sql语句

最后的sql语句结构以下程序

select a.time_str,

case when b.num is null then 0 else b.num end

from(

select  '20190303' time_str

UNION ALL

select  '20190304' time_str

...

UNION ALL

select  '20190401' time_str ) a

left  join (

select time_str,count(*) num from table group by time_str

)b on a.time_str=b.time_str


版权声明:本文为weixin_39608118原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。