也许在开发的时候我们会头疼需要统计各种报表数据,mysql语句写的都是超长超复杂的,那么总有解决的办法,现在小编就给大家分享一些比较基础的sql关于时间方面的统计知识。
现在假设有这样一张订单数据表:
create table `order` (
`id` int(11) unsigned not null auto_increment,
`order_sn` varchar(50) character set utf8 not null default '' comment '订单编号,保证唯一',
`create_at` int(11) not null default '0' comment '创建时间',
`success_at` int(11) not null default '0' comment '订单完成时间',
`creator_id` varchar(50) character set utf8 not null default '' comment '订单创建人',
primary key (`id`),
unique key `uni_sn` (`order_sn`),
) engine=innodb auto_increment=1 default charset=utf8mb4 collate=utf8mb4_unicode_ci comment='订单表';
现在以如上表为例查询相关的数据:
查询今天所有已完成的订单编号:
select `order_sn` from `order` where yearweek(from_unixtime(success_at,'%y-%m-%d')) = date_format(now(),'%y-%m-%d');
查询当前这周所有已完成的订单编号:
select `order_sn` from `order` where yearweek(from_unixtime(success_at,'%y-%m-%d')) = yearweek(now());
查询上周所有已完成的订单编号:
select `order_sn` from `order` where yearweek(from_unixtime(success_at,'%y-%m-%d')) = yearweek(now())-1;
查询当前月份所有已完成的订单编号:
select `order_sn` from `order` where from_unixtime(success_at,'%y-%m')=date_format(now(),'%y-%m');
查询上个月份所有已完成的订单编号:
select `order_sn` from `order` where from_unixtime(success_at,'%y-%m')=date_format(date_sub(curdate(), interval 1 month),'%y-%m');
查询距离当前现在6个月已完成的订单编号:
select `order_sn` from `order` where from_unixtime(success_at,'%y-%m-%d %h:%i:%s') between date_sub(now(),interval 6 month) and now();
查询本季度所有已完成的订单编号:
select `order_sn` from `order` where quarter(from_unixtime(success_at,'%y-%m-%d'))=quarter(now());
查询上季度所有已完成的订单编号:
select `order_sn` from `order` where quarter(from_unixtime(success_at,'%y-%m-%d'))=quarter(date_sub(now(),interval 1 quarter));
查询本年所有已完成的订单编号:
select `order_sn` from `order` where year(from_unixtime(success_at,'%y-%m-%d'))=year(now());
查询上年所有已完成的订单编号:
select `order_sn` from `order` where year(from_unixtime(success_at,'%y-%m-%d'))=year(date_sub(now(),interval 1 year));
以上内容就是mysql查询报表时间的相关教程,希望对大家有帮助。
相关推荐:
mysql查询时间的相关知识
mysql查询时间段的方法示例代码
mysql查询时间日期的方法与函数
以上就是mysql查询时间基础教程的详细内容。