1.查询近7天得数据
2.由于公司需要对时间格式取月日进行处理
3.完善部分月份无数据得情况下设值为0
select gas_date as datess,number as num from (select * from fd_rq_gas_patrol where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=date(gas_date) ORDER BY gas_date) as sss GROUP BY datess
查询结果为:
对时间进行处理
select DATE_FORMAT(gas_date,'%m-%d') datess,number as num from (select * from fd_rq_gas_patrol where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=date(gas_date) ORDER BY gas_date) as sss GROUP BY datess
后来发现如果缺少部分月份数据录入就会导致结果理论上要7条,但实际结果就少于7条。
后面去网上翻阅了下资料找到一位大佬得思路是创建一张虚表查出来近七天得时间。再连接两张表进行查询就能补充上缺少得月份数据了。
创建虚表查询近七天数据
union all 是互相连接查询结果,
SELECT curdate() as ouo_date union all SELECT DATE_SUB(curdate(), interval 6 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 5 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 4 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 3 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 2 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 1 day) as ouo_date
最终将两表结果通过LEFT JOIN合并起来,根据时间相等
select DATE_FORMAT(ouo_date,'%m-%d') ouo_date,IFNULL(b.num,0) num from( SELECT curdate() as ouo_date union all SELECT DATE_SUB(curdate(), interval 6 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 5 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 4 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 3 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 2 day) as ouo_date union all SELECT DATE_SUB(curdate(), interval 1 day) as ouo_date ) a left join ( select gas_date as datess,number as num from (select * from fd_rq_gas_patrol where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=date(gas_date) ORDER BY gas_date) as sss GROUP BY datess ) b on a.ouo_date=b.datess ORDER BY a.ouo_date
结果如下图
此处主要使用 IFNULL进行为null设置为0,还有另外一种case when得写法,但是那种不是很美观。