When we extract data with Mysql, often need to group the data statistics according to different granularity days, weeks, months, and so on. And our time might be "2017/12/5 0: 0: 0" this exact time. So before making a packet time we need to look at treatment.
MySQL is built DATE_FORMAT a function, acting in a different format date / time data. The syntax is as follows:
DATE_FORMAT (date, format), wherein
date: legal date. format: a predetermined output format of the date / time format in which the format may be used, see the end the link.
The following statistics are grouped by how we DATE_FORMAT look through concrete examples:
The following table represent the two products to buy the exact time (accurate to the second), and the type of product to buy.
product_no start_time
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
Now we need to daily, weekly, monthly sales of each product statistics,
1) by day statistics:
select DATE_FORMAT(start_time,'%Y%m%d') days,count(product_no) count from test group by days;
2) weekly statistics:
select DATE_FORMAT(start_time,'%Y%u') weeks,count(product_no) count from test group by weeks;
3) Monthly:
select DATE_FORMAT(start_time,'%Y%m') months,count(product_no) count from test group bymonths;