题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/monthly-transactions-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本人思路:
– 1、注意思路清晰,先找到 每月每个国家/地区的已批准交易的数量 和 每月每个国家/地区的退单的数量 并使用union all连接
– 2、注意退单数量的求法,内连接Chargebacks 表,因为有些订单是state = 'approved’但之后退单了,所以用0,1标签来区别未退单的,并返回退单的月份
– 3、由1,2可以得到临时表temp,再根据month,country分组,即可得到每个月和每个国家/地区的已批准交易的数量及其总金额、退单的数量及其总金额。
– Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;
– Union All:对两个结果集进行并集操作,包括重复行,不进行排序
select month, country,
count(case when state = 'approved' and tag=0 then 1 else null end) as approved_count,
sum(case when state = 'approved' and tag =0 then amount else 0 end)as approved_amount,
count(case when tag =1 then 1 else null end)as chargeback_count,
sum(case when tag =1 then amount else 0 end)as chargeback_amount
from
(
-- 每个月和每个国家/地区的已批准交易的数量
select id,country,state,amount,date_format(trans_date ,"%Y-%m")as month,0 as tag
from Transactions
where state = 'approved'
union all
-- 每个月和每个国家/地区的退单的数量
select id,country,state,amount,date_format(c.trans_date ,"%Y-%m")as month,1 as tag
from Transactions as t inner join Chargebacks as c
on t.id = c.trans_id
)temp
group by month,country