转自:https://blog.csdn.net/u010324331/article/details/84343946
本文章 mysql 统计使用到的函数说明
DATE_FORMAT(日期时间,格式)
FROM_UNIXTIME(时间戳,格式)
格式 说明
%a 缩写星期名
%b 缩写月名
%c 月,数值
%D 带有英文前缀的月中的天
%d 月的天,数值 (00-31)
%e 月的天,数值 (0-31)
%f 微秒
%H 小时 (00-23)
%h 小时 (01-12)
%I 小时 (01-12)
%i 分钟,数值 (00-59)
%j 年的天 (001-366)
%k 小时 (0-23)
%l 小时 (1-12)
%M 月名
%m 月,数值 (00-12)
%p AM 或 PM
%r 时间,12 - 小时(hh:mm:ss AM 或 PM)
%S 秒 (00-59)
%s 秒 (00-59)
%T 时间, 24 - 小时 (hh:mm:ss)
%U 周 (00-53) 星期日是一周的第一天
%u 周 (00-53) 星期一是一周的第一天
%V 周 (01-53) 星期日是一周的第一天,与 %X 使用
%v 周 (01-53) 星期一是一周的第一天,与 %x 使用
%W 星期名
%w 周的天 (0 = 星期日, 6 = 星期六)
%X 年,其中的星期日是周的第一天,4 位,与 %V 使用
%x 年,其中的星期一是周的第一天,4 位,与 %v 使用
%Y 年,4 位
%y 年,2 位
// 统计 7 天内每天的数量
时间字段时间戳格式
# 统计 7 天每天关注的人数
SELECT
FROM_UNIXTIME( subscribe_date, '%Y-%m-%d' ) AS date,
COUNT( * ) AS count
FROM
sys_weixin_fans
WHERE
is_subscribe = 1
AND subscribe_date > 1535558400
AND subscribe_date < 1536163200
GROUP BY
date
ORDER BY
date ASC
时间字段日期时间格式:
# 统计 7 天每天的新增的积分和订单总金额
SELECT
DATE_FORMAT( time, '%Y-%m-%d' ) AS date,
COUNT( * ) AS count,
sum( add_points ) AS add_points,
sum( amount ) AS amount
FROM
`sys_order`
WHERE
( `time` > '2018-08-30' AND `time` < '2018-09-06' )
GROUP BY
date
ORDER BY
date ASC
其他使用示例
按小时:
SELECT
from_unixtime( create_time, "%Y%m%d%H" ) AS hours,
count( id ) AS counts
FROM
`table`
GROUP BY
hours;
按日:
SELECT
from_unixtime( create_time, "%Y-%m-%d" ) AS days,
count( id ) AS counts
FROM
`table`
GROUP BY
days;
按周:
SELECT
from_unixtime( create_time, "%Y-%u" ) AS weeks,
count( id ) AS counts
FROM
`table`
GROUP BY
weeks;
按月:
SELECT
from_unixtime( create_time, "%Y-%m" ) AS months,
count( id ) AS counts
FROM
`table`
GROUP BY
months;
按季度:
SELECT
concat( from_unixtime( create_time, "%Y" ), floor( ( from_unixtime( create_time, "%m" ) + 2 ) / 3 ) ) AS quarters,
count( id ) AS counts
FROM
`table`
GROUP BY
quarters;
按年:
SELECT
from_unixtime( create_time, "%Y" ) AS years,
count( id ) AS counts
FROM
`table`
GROUP BY
years;