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

相信不少人的项目都有这种需求,就是查询近7天的记录,可是这7天总有那么几天是没数据的,因此缺失的只能补 0 数据库

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

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

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

2.1)先查询本身想要的数据,用天天分组,计算好总数后unix

2.2)时间戳字段先转日期io

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

而后~~~~而后就大功告成啦date

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.datetimeselect

相关文章
相关标签/搜索