每日一题-72(每月交易2)

题72:

根据下表编写一个 SQL 查询,以查找每个月和每个国家/地区的信息,已批准交易的数量及其总金额、退单的数量及其总金额。
注意:在您的查询中,只需显示给定月份和国家,忽略所有为零的行。
在这里插入图片描述
其中:

  • Transactions 表:id 是这个表的主键,该表包含有关传入事务的信息,状态列是类型为 [approved(已批准)、declined(已拒绝)] 的枚举;
  • Chargebacks 表:退单包含有关放置在事务表中的某些事务的传入退单的基本信息,trans_id 是 transactions 表的 id 列的外键,每项退单都对应于之前进行的交易,即使未经批准。

解题思路:
(1)首先查出每个月和每个国家/地区的已批准交易的数量集其总金额;
(2)在查出每个月和每个国家/地区的退单的数量及其总金额;
(3)然后用union all进行合并
(4)最后统计、求和加分组排序即可

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 country,state,amount,date_format(c.trans_date,'%Y-%m') as month,1 as tag
    from Transactions t   
    right join Chargebacks c on t.id=c.trans_id
    union all
    select country,state,amount,date_format(t.trans_date,'%Y-%m') as month,0  as tag
    from Transactions t  
    where state!='declined'
) a 
group by country,month 
order by month,country;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值