最近因工作的需要,需要统计各种报表数据,SQL语句写的都是超长超复杂的,现在仅总结一些比较基础的SQL关于时间方面的统计知识。
现在假设有这样一张订单数据表:
1 | CREATE TABLE ` order ` ( |
2 | `id` int (11) unsigned NOT NULL AUTO_INCREMENT, |
3 | `order_sn` varchar (50) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '订单编号,保证唯一' , |
4 | `create_at` int (11) NOT NULL DEFAULT '0' COMMENT '创建时间' , |
5 | `success_at` int (11) NOT NULL DEFAULT '0' COMMENT '订单完成时间' , |
6 | `creator_id` varchar (50) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '订单创建人' , |
7 | PRIMARY KEY (`id`), |
8 | UNIQUE KEY `uni_sn` (`order_sn`), |
9 | ) 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));