mysql 查询近7天数据,缺失补0

时间:2023-03-09 16:43:10
mysql 查询近7天数据,缺失补0

相信很多人的项目都有这种需求,就是查询近7天的记录,但是这7天总有那么几天是没数据的,所以缺失的只能补 0

下面的代码不知道能不能看懂,我简单的说一下思路

1)先查询红色字体的近7天,再转换成日期

2)我的字段使用的是时间戳的方式去保存,只能是先数据库字段先转日期

2.1)先查询自己想要的数据,用每天分组,计算好总数后

2.2)时间戳字段先转日期

2.3)用 ifnull 函数判断,缺失就补 0

然后~~~~然后就大功告成啦

select temp.days, ifnull(walletTemp.money, 0) as money from (
SELECT curdate() as days
union all
SELECT date_sub(curdate(), interval 1 day) as days
union all
SELECT date_sub(curdate(), interval 2 day) as days
union all
SELECT date_sub(curdate(), interval 3 day) as days
union all
SELECT date_sub(curdate(), interval 4 day) as days
union all
SELECT date_sub(curdate(), interval 5 day) as days
union all
SELECT date_sub(curdate(), interval 6 day) as days ) as temp
left join
(select date(FROM_UNIXTIME(createAt, '%Y%m%d')) as datetime, sum(money) as money
from wb_car_wallet where driverId = 'e472e99da1be45918c82d92753382ac3'
and type = 0 or type = 1
group by from_unixtime(createAt, '%Y-%m-%d')
order by createAt) as walletTemp on temp.days = walletTemp.datetime