题解 | #计算商城中2021年每月的GMV#
计算商城中2021年每月的GMV
https://www.nowcoder.com/practice/5005cbf5308249eda1fbf666311753bf
逆向求解,
首先我们用 case when 语句把 0和1 对应的值变为1,把2对应的值变为0,添加成state这一列,构建一个新表t2
接着,要想求出2021年每个月的GMV,那么我们先求出每天的GMV,total_amount*state过滤掉了退货的情况,得到表t1
最后,按照月份聚合,得到我们想要的结果
select
date_format(dt, '%Y-%m') month,
round(sum(tz), 0) GMV
from
(SELECT date(event_time) dt,
sum(total_amount * state ) tz
from
(select * ,
case status when 1 then 1 when 0 then 1 else 0 end state
from tb_order_overall
) t2
where date_format(date(event_time), '%Y') = 2021
group by dt
) t1 -- 得到表1
group by month
having GMV > 100000
order by GMV