您的位置:首页 > 数据库 > MySQL

Mysql按小时,按日,按周,按月,按季度,按年分组统计数据

2018-03-14 15:37 681 查看
按小时:
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;

查询本年度数据:
select * from table where year(from_unixtime(create_time))=year(curdate());

查询本季度数据:
select * from table where concat(year(from_unixtime(create_time)),quarter(from_unixtime(create_time)))
=concat(year(curdate()),quarter(curdate()));
查询数据中附带季度数据:
select concat(from_unixtime(create_time,"%Y"),"-",quarter(from_unixtime(create_time))) as quarters,id from table;
查询本月数据:
select * from table where month(from_unixtime(create_time))=month(curdate()) 
and year(from_unixtime(create_time))=year(curdate());
查询本周数据:
select * from table where  year(from_unixtime(create_time))=year(curdate()) 
and month(from_unixtime(create_time))=month(curdate()) 
and week(from_unixtime(create_time))=week(curdate());

查询N天内的数据:
select * from table where (to_days(now()) - to_days(from_unixtime(create_time)))<=N;

函数:from_unixtime
作用:将MYSQL中以INT(11)存储的时间以"YYYY-MM-DD"格式来显示。
语法:from_unixtime(unix_timestamp,format)返回表示 Unix 时间标记的一个字符串,根据format字符串格式化。format可以包含与date_format()函数列出的条目同样的修饰符。根据format字符串格式化date值。
下列修饰符可以被用在format字符串中:%M 月名字(January……December)
%W 星期名字(Sunday……Saturday)
%D 有英语前缀的月份的日期(1st, 2nd, 3rd, 等等。)
%Y 年, 数字, 4 位
%y 年, 数字, 2 位
%a 缩写的星期名字(Sun……Sat)
%d 月份中的天数, 数字(00……31)
%e 月份中的天数, 数字(0……31)
%m 月, 数字(01……12)
%c 月, 数字(1……12)
%b 缩写的月份名字(Jan……Dec)
%j 一年中的天数(001……366)
%H 小时(00……23)
%k 小时(0……23)
%h 小时(01……12)
%I 小时(01……12)
%l 小时(1……12)
%i 分钟, 数字(00……59)
%r 时间,12 小时(hh:mm:ss [AP]M)
%T 时间,24 小时(hh:mm:ss)
%S 秒(00……59)
%s 秒(00……59)
%p AM或PM
%w 一个星期中的天数(0=Sunday ……6=Saturday )
%U 星期(0……52), 这里星期天是星期的第一天
%u 星期(0……52), 这里星期一是星期的第一天
%% 一个文字“%”。例子:select from_unixtime(1218196800, '%Y-%m-%d %H:%i:%S')selec
9098
t *,[b]from_unixtime
(create_time, '%Y-%m-%d') as times from table;[/b]

注:文章中create_time为时间戳格式,from_unixtime带的时间格式也可以自由更改。文章部分文字内容有转载,如有侵权,请及时联系。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: