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

我们在用 Mysql 制作数据可视化图表时候,经常需要按照天、周、月等不同的粒度对数据进行分组统计。而我们的时间可能是 “2017/12/5 0:0:0” 这种准确的时间。

所以在进行分组之前我们需要对时间进行处理。

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

DATE_FORMAT(date,format)

其中

date:合法的日期

format:规定日期/时间的输出格式,其中format可使用的格式可以查看以下链接

https://www.w3school.com.cn/sql/func_date_format.asp

 

下面我们通过具体例子来看如何通过 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; 

 



posted @ 2019-09-25 15:46  Ryan_zheng  阅读(708)  评论(0编辑  收藏  举报