1205 每月交易II leetcode数据库刷题 (没写出来)

1205 每月交易II
sql 架构;

create table if not exists Transactions (id int, country varchar(4), state enum('approved', 'declined'), amount int, trans_date date)
create table if not exists Chargebacks (trans_id int, trans_date date)
Truncate table Transactions
insert into Transactions (id, country, state, amount, trans_date) values ('101', 'US', 'approved', '1000', '2019-05-18')
insert into Transactions (id, country, state, amount, trans_date) values ('102', 'US', 'declined', '2000', '2019-05-19')
insert into Transactions (id, country, state, amount, trans_date) values ('103', 'US', 'approved', '3000', '2019-06-10')
insert into Transactions (id, country, state, amount, trans_date) values ('104', 'US', 'declined', '4000', '2019-06-13')
insert into Transactions (id, country, state, amount, trans_date) values ('105', 'US', 'approved', '5000', '2019-06-15')
Truncate table Chargebacks
insert into Chargebacks (trans_id, trans_date) values ('102', '2019-05-29')
insert into Chargebacks (trans_id, trans_date) values ('101', '2019-06-30')
insert into Chargebacks (trans_id, trans_date) values ('105', '2019-09-18')

在这里插入图片描述
mysql 没有full join 的用法
注意这里销售表没有 09月,可是退款表却有9月,连接起来的话 使用union all 注意匹配字段

select  id,country,state,amount,substr(trans_date,1,7) as 'trans_date'
from  Transactions
union all 

select trans_id,country, 
#'Chargebacks'  as state,amount, 为了匹配字段且不影响上面的状态
'Chargebacks'  as state,amount, substr(c.trans_date,1,7) as 'trans_date'
from Chargebacks c 
left join Transactions t  on c.trans_id = t.id 

本题最关键还就是这里的union all

在这里插入图片描述
这里注意过滤0行的情况

# Write your MySQL query statement below


SELECT z.trans_date as 'month',z.country,
#已批准交易的数量
sum(if(z.state = 'approved',1,0)) as 'approved_count',
#已批准交易的总金额
sum(if(z.state = 'approved',z.amount,0)) as 'approved_amount',
#退单的数量
sum(if(z.state = 'Chargebacks',1,0)) as 'chargeback_count',
#退单的总金额
sum(if(z.state = 'Chargebacks',z.amount,0)) as 'chargeback_amount'

FROM
(select  id,country,state,amount,substr(trans_date,1,7) as 'trans_date'
from  Transactions
union all #因为没带主键id,不all的话可能去重去掉有效数据

select trans_id as 'id',country, 
#'Chargebacks'  as state,amount, 为了匹配字段且不影响上面的状态
'Chargebacks'  as state,amount, substr(c.trans_date,1,7) as 'trans_date'
from Chargebacks c 
left join Transactions t  on c.trans_id = t.id ) z

group by z.trans_date,z.country 
#,忽略所有为零的行
having sum(if(z.state = 'approved',1,0)) or sum(if(z.state = 'Chargebacks',1,0)) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值