zoukankan      html  css  js  c++  java
  • mysql查询最近7天的数据,没有数据自动补0

    问题描述

    查询数据库表中最近7天的记录

    select count(*),date(create_time) as date from task where datediff(now(),create_time)<=6  group by day(create_time); 

     

    但是发现某一天没有数据,结果中没有显示当天(2017-08-28)的数据

    这里写图片描述

    解决思路

    1. 思路一: 可以在自己的程序中做额外的补零处理

    2. 思路二: 构建一个最近七天的结果集,然后和查询的结果集合做left join(本文采用第二种方式)

    select a.click_date,b.count
    from (
        SELECT curdate() as click_date
        union all
        SELECT date_sub(curdate(), interval 1 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 2 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 3 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 4 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 5 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 6 day) as click_date
    ) a left join (
      select date(create_time) as datetime, count(*) as count
      from arms_task
      group by date(create_time)
    ) b on a.click_date = b.datetime;

    当天2017-08-28结果显示为NULL

    这里写图片描述

    需要把NULL设置为0,利用ifnull函数即可

    select a.click_date,ifnull(b.count,0) as count
    from (
        SELECT curdate() as click_date
        union all
        SELECT date_sub(curdate(), interval 1 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 2 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 3 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 4 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 5 day) as click_date
        union all
        SELECT date_sub(curdate(), interval 6 day) as click_date
    ) a left join (
      select date(create_time) as datetime, count(*) as count
      from arms_task
      group by date(create_time)
    ) b on a.click_date = b.datetime;

    这里写图片描述

  • 相关阅读:
    Redis常用操作命令
    redis-sentinel.conf配置项详解
    Kafka常用命令
    go modules的使用姿势
    GO语言密码加解密(bcrypt)
    ssh-copy-id 秘钥分发报错
    k8s 命令提示
    算法与数据结构(持续更新)
    【spring】 @PostConstruct注解
    Spring Boot 整合Redis
  • 原文地址:https://www.cnblogs.com/snake23/p/9562646.html
Copyright © 2011-2022 走看看