Medium之1205.每月交易II***

Table: Transactions

Column NameType
idint
countryvarchar
stateenum
amountint
trans_datedate

id 是这个表的主键。
该表包含有关传入事务的信息。
状态列是类型为 [approved(已批准)、declined(已拒绝)] 的枚举。

Chargebacks 表

Column NameType
trans_idint
trans_datedate

退单包含有关放置在事务表中的某些事务的传入退单的基本信息。
trans_id 是 transactions 表的 id 列的外键。
每项退单都对应于之前进行的交易,即使未经批准。

问题

编写一个 SQL 查询,以查找每个月和每个国家/地区的信息:已批准交易的数量及其总金额、退单的数量及其总金额。

注意:在您的查询中,只需显示给定月份和国家,忽略所有为零的行。

示例

Transactions 表:

idcountrystateamounttrans_date
101USapproved10002019-05-18
102USdeclined20002019-05-19
103USapproved30002019-06-10
104USdeclined40002019-06-13
105USapproved50002019-06-15

Chargebacks 表:

trans_idtrans_date
1022019-05-29
1012019-06-30
1052019-09-18

Result 表:

monthcountryapproved_countapproved_amountchargeback_countchargeback_amount
2019-05US1100012000
2019-06US2800011000
2019-09US0015000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/monthly-transactions-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答

select left(trans_date,7) as month,
       country,
       count(if(state = 'approved',1,null)) as approved_count,
       sum(if(state = 'approved',amount,0)) as approved_amount,
       sum(state='chargeback') as chargeback_count,
       sum(if(state = 'chargeback',amount,0)) as chargeback_amount
from(
    select * from transactions
    union all
    select id,country,'chargeback' as state,amount,c.trans_date
    from transactions t 
         right join 
         chargebacks c on c.trans_id = t.id  
    ) tmp
group by month,country
having approved_amount or chargeback_amount
知识点

1.union all:考虑点:两个表的时间不是完全对应或者完全归属的,如果不使用union all会出现漏掉日期字段的情况。

2.having approved_amount or chargeback_amount
:用于保证approved_amount或者chargeback_amount至少有一个不为0(基于题目中条件:只需显示给定月份和国家,忽略所有为零的行)。

3.count(if(state = ‘approved’,1,null)) = sum(state = ‘approved’)
因为sum(条件):对符合条件的结果行数进行求和

4.提取月份
date_format(trans_date, ‘%Y-%m’) month
或者left(trans_date,7) as month

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值