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

  我们在用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 bymonths; 

 

官网 DATE_FROMAT 函数

官网日期时间函数

posted @ 2019-08-08 18:11  Ryan_zheng  阅读(8107)  评论(0编辑  收藏  举报