• 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

  • 相关阅读:
    CF676E:The Last Fight Between Human and AI
    BZOJ2079: [Poi2010]Guilds
    BZOJ4518: [Sdoi2016]征途
    BZOJ2216: [Poi2011]Lightning Conductor
    51nod1766 树上的最远点对
    洛谷P1257 平面上的最接近点对
    BZOJ2144: 跳跳棋
    BZOJ4773: 负环
    BZOJ4552: [Tjoi2016&Heoi2016]排序
    The Falling Leaves(建树方法)
  • 原文地址:https://www.cnblogs.com/xjbBill/p/8510541.html
Copyright © 2020-2023  润新知