MySql教程

MYSQL查询近一周数据并且为空得数据自动赋值为0

本文主要是介绍MYSQL查询近一周数据并且为空得数据自动赋值为0,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

部分数据库样版

在这里插入图片描述

思路

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得写法,但是那种不是很美观。

在这里插入图片描述

这篇关于MYSQL查询近一周数据并且为空得数据自动赋值为0的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!