MySQL按日、周、月进行分组统计

2022年 5月 20日 43点热度 0人点赞

原文链接:https://blog.csdn.net/lz_peter/article/details/78722976

引言

我们在用 MySQL 抽取数据时候, 经常需要按照天, 周, 月等不同的粒度对数据进行分组统计. 而我们的时间可能是 "2017/12/5 0:0:0" 这种准确的时间. 所以在进行分组之前我们需要对时间进行一下处理.

语法

DATE_FORMAT 是 MySQL 内置的一个函数, 作用是以不同的格式显示日期/时间数据. 具体的语法如下:

DATE_FORMAT(date,format)

其中

  • date: 合法的日期.
  • format: 规定日期/时间的输出格式, 其中 format 可使用的格式见文末链接.

示例

下面我们通过具体例子来看如何通过 DATE_FORMAT 进行分组统计:

下表两列分别代表产品买出的准确时间 (精确到秒), 和买出的产品类型.

start_time product_no
2017/12/1 00:00:11 2A
2017/12/3 07:51:11 3C
2017/12/3 07:59:25 3C
2017/12/5 15:40:45 6C

现在我们需要对每天, 每周, 每月各个产品的销量进行统计.

1) 按天统计:

select DATE_FORMAT(start_time,'%Y%m%d') days,count(product_no) count from test group by days;

2) 按周统计:

select DATE_FORMAT(start_time,'%Y%u') weeks,count(product_no) count from test group by weeks;

3) 按月统计:

select DATE_FORMAT(start_time,'%Y%m') months,count(product_no) count from test group by months;

参考

rainbow

这个人很懒,什么都没留下

文章评论