MySQL查询近七天数据 无数据补零

构建一个最近7天日期的结果集连接要查询的表,没有数据的通过ifnull函数补零;
这里create_time字段为时间戳格式,所以需要转换成yyyy-MM-dd的格式

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 FROM_UNIXTIME(create_time,'%Y-%m-%d') AS dt, SUM(loanAmt) AS amt
  FROM t_loanmerpay
  GROUP BY dt
) b ON a.click_date = b.dt
ORDER BY a.click_date ASC;

你可能感兴趣的:(MySQL查询近七天数据 无数据补零)