mysql按月统计六个月内不同类型订单的成交金额
创建数据库
CREATE DATABASE test;
创建订单表
CREATE TABLE `t_order` (`id` bigint(4) NOT NULL AUTO_INCREMENT COMMENT '主键,自增', `source` smallint(1) NOT NULL COMMENT '订单来源:1:商城 2:订单导入',`status` smallint(1) NOT NULL COMMENT '订单状态:1: 待确认 2:已确认 3:已完成',`order_amt` decimal(20,8) NOT NULL COMMENT '订单总金额',`create_user_id` bigint(4) DEFAULT NULL COMMENT '创建人id',`create_time` datetime DEFAULT NULL COMMENT '创建日期',PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='订单表';
此处订单表只涉及统计需要的字段,实际开发应该会复杂一些。
插入测试数据
INSERT INTO `t_order` (`id`, `source`, `status`, `order_amt`, `create_user_id`, `create_time`) VALUES ('1', '1', '2', '8000.00000000', '1', '2018-01-01 22:12:41'); INSERT INTO `t_order` (`id`, `source`, `status`, `order_amt`, `create_user_id`, `create_time`) VALUES ('2', '2', '3', '9000.00000000', '1', '2018-05-16 22:13:24'); INSERT INTO `t_order` (`id`, `source`, `status`, `order_amt`, `create_user_id`, `create_time`) VALUES ('3', '1', '3', '5000.00000000', '1', '2018-01-17 22:14:00'); INSERT INTO `t_order` (`id`, `source`, `status`, `order_amt`, `create_user_id`, `create_time`) VALUES ('4', '1', '3', '12000.00000000', '2', '2017-11-16 22:15:03'); INSERT INTO `t_order` (`id`, `source`, `status`, `order_amt`, `create_user_id`, `create_time`) VALUES ('5', '2', '3', '7000.00000000', '2', '2018-04-18 22:15:43');
统计六个月内不同类型已完成状态订单的成交额
SELECTsix_month.`month` `month`,source.source source,IFNULL(SUM(o.order_amt), 0) orderAmt FROM(SELECT DATE_FORMAT(now(), '%Y-%c') month FROM DUALUNION ALL SELECT DATE_FORMAT(date_sub(now(), INTERVAL 1 MONTH), '%Y-%c') month FROM DUALUNION ALL SELECT DATE_FORMAT(date_sub(now(), INTERVAL 2 MONTH), '%Y-%c') month FROM DUALUNION ALL SELECT DATE_FORMAT(date_sub(now(), INTERVAL 3 MONTH), '%Y-%c') month FROM DUALUNION ALL SELECT DATE_FORMAT(date_sub(now(), INTERVAL 4 MONTH), '%Y-%c') month FROM DUALUNION ALL SELECT DATE_FORMAT(date_sub(now(), INTERVAL 5 MONTH), '%Y-%c') month FROM DUAL) six_month CROSS JOIN (SELECT 1 source FROM DUALunion all SELECT 2 source FROM DUAL ) source LEFT JOIN t_order o ON o.source = source.source AND DATE_FORMAT(o.create_time, '%Y-%c') = six_month.`month` AND `status` = 3 GROUP BYsix_month.`month`,source.source;
统计结果
从结果可以看出,统计出了最近六个月内每个月每一种订单类型的已完成状态的订单的成交额。