【LeetCode刷题】数据库之中等题:1205. 每月交易II

题目:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
分析:该题分了两种情况,分别是approved,和 chargebasks的情况,而且出现了两个日期,因此直接采用join是行不通的,只能用合并的方式。结果中的年月用date_format(date,format)实现。

解法:

  1. 查出满足state='approved’条件的各类信息。
select country,state,amount,date_format(trans_date,"%Y-%m") as month,1 as tag
from Transactions
where state='approved'
  1. 再查出回退单子(chargebasks)的信息,此处需要right join chargebasks表,然后跟上面的union all合并。
select country,state,amount,date_format(c.trans_date,"%Y-%m") as month,0 as tag
from Transactions t right join Chargebacks c
on c.trans_id=t.id
  1. 最后用count,sum根据条件聚合,再根据country,month分组。

▲这里使用tag是为了更好的区分两种不同情况

解:

select month,
country,
count(case when state='approved' and tag=1 then 1 end) as approved_count,
sum(case when tag=1 then amount else 0 end) as approved_amount,
count(case when tag=0 then 1 end) as chargeback_count,
sum(case when tag=0 then amount else 0 end) as chargeback_amount
from(
    select country,state,amount,date_format(trans_date,"%Y-%m") as month,1 as tag
from Transactions
where state='approved'
union all
select country,state,amount,date_format(c.trans_date,"%Y-%m") as month,0 as tag
from Transactions t right join Chargebacks c
on c.trans_id=t.id
) as a
group by month,country;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值