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

相關文章
相關標籤/搜索