当前位置:   article > 正文

mysql查询最近7天的数据?

mysql查询最近7天的数据?

1.只显示有记录的数据

SELECT 
	DATE_FORMAT(create_time,"%Y-%m-%d") as createtimes,
	COUNT(*) as nums
	FROM USER 
	where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time) 
	GROUP BY DATE_FORMAT(create_time,"%Y-%m-%d")
	ORDER BY DATE_FORMAT(create_time,"%Y-%m-%d") DESC
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

结果:只会记录有值的
在这里插入图片描述

2.要求显示每一天的数据量,为空则填充0

select a.click_date,ifnull(b.nums,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_FORMAT(create_time,"%Y-%m-%d") as createtimes,
	COUNT(*) as nums
	FROM `user` 
	where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time) 
	GROUP BY DATE_FORMAT(create_time,"%Y-%m-%d")
	ORDER BY DATE_FORMAT(create_time,"%Y-%m-%d") DESC
) b on a.click_date = b.createtimes ORDER BY a.click_date asc

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/230749
推荐阅读
相关标签
  

闽ICP备14008679号