SQL168. 计算商城中2021年每月的GMV
描述
现有订单总表tb_order_overall
id | order_id | uid | event_time | total_amount | total_cnt | status |
1 | 301001 | 101 | 2021-10-01 10:00:00 | 15900 | 2 | 1 |
2 | 301002 | 101 | 2021-10-01 11:00:00 | 15900 | 2 | 1 |
3 | 301003 | 102 | 2021-10-02 10:00:00 | 34500 | 8 | 0 |
4 | 301004 | 103 | 2021-10-12 10:00:00 | 43500 | 9 | 1 |
5 | 301005 | 105 | 2021-11-01 10:00:00 | 31900 | 7 | 1 |
6 | 301006 | 102 | 2021-11-02 10:00:00 | 24500 | 6 | 1 |
7 | 301007 | 102 | 2021-11-03 10:00:00 | -24500 | 6 | 2 |
8 | 301008 | 104 | 2021-11-04 10:00:00 | 55500 | 12 | 0 |
month | GMV |
2021-10 | 109800 |
2021-11 | 111900 |
示例1
输入:
DROP TABLE IF EXISTS tb_order_overall; CREATE TABLE tb_order_overall ( id INT PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID', order_id INT NOT NULL COMMENT '订单号', uid INT NOT NULL COMMENT '用户ID', event_time datetime COMMENT '下单时间', total_amount DECIMAL NOT NULL COMMENT '订单总金额', total_cnt INT NOT NULL COMMENT '订单商品总件数', `status` TINYINT NOT NULL COMMENT '订单状态' ) CHARACTER SET utf8 COLLATE utf8_bin; INSERT INTO tb_order_overall(order_id, uid, event_time, total_amount, total_cnt, `status`) VALUES (301001, 101, '2021-10-01 10:00:00', 15900, 2, 1), (301002, 101, '2021-10-01 11:00:00', 15900, 2, 1), (301003, 102, '2021-10-02 10:00:00', 34500, 8, 0), (301004, 103, '2021-10-12 10:00:00', 43500, 9, 1), (301005, 105, '2021-11-01 10:00:00', 31900, 7, 1), (301006, 102, '2021-11-02 10:00:00', 24500, 6, 1), (391007, 102, '2021-11-03 10:00:00', -24500, 6, 2), (301008, 104, '2021-11-04 10:00:00', 55500, 12, 0);
输出:
2021-10|109800 2021-11|111900
Mysql 解法, 执行用时: 36ms, 内存消耗: 6384KB, 提交时间: 2022-02-09
select date_format(event_time,"%Y-%m") month,sum(total_amount) GMV from tb_order_overall where status in (1,0) and year(event_time) = 2021 group by month having GMV > 100000 order by GMV
Mysql 解法, 执行用时: 36ms, 内存消耗: 6412KB, 提交时间: 2021-12-18
select date_format(event_time,'%Y-%m') as month,round(sum(total_amount),0) as GMV from tb_order_overall where event_time like '2021%' and status <> 2 group by date_format(event_time,'%Y-%m') having round(sum(total_amount),0)>100000 order by GMV asc;
Mysql 解法, 执行用时: 36ms, 内存消耗: 6412KB, 提交时间: 2021-12-12
-- 2021年12月11日 -- GMV为已付款订单和未付款订单两者之和。结果按GMV升序排序。 select date_format(event_time,'%Y-%m') as month , sum(total_amount) as GMV from tb_order_overall where `status` in (0,1) and year(event_time)=2021 group by date_format(event_time,'%Y-%m') having sum(total_amount) > 100000 order by GMV ;
Mysql 解法, 执行用时: 36ms, 内存消耗: 6452KB, 提交时间: 2022-01-01
SELECT DATE_FORMAT(event_time,'%Y-%m') as month, round(sum(total_amount),0) as GMV FROM (SELECT * from tb_order_overall where total_amount > 0) as result where YEAR(event_time)=2021 group by month HAVING GMV >100000 order by GMV
Mysql 解法, 执行用时: 36ms, 内存消耗: 6464KB, 提交时间: 2022-01-01
SELECT DATE_FORMAT(event_time,'%Y-%m') month,sum(total_amount) GMV FROM tb_order_overall WHERE status != 2 AND year(event_time)=2021 GROUP BY month HAVING GMV >= 100000 ORDER BY GMV;