1193. 每月交易 I


解题思路:这里trans_count,trans_total_amount是针对全部数据的,而approved_total_amount,approved_total_amount

是针对部分的,所以就想着分别求出,然后根据字段month和country相同进行合并。所以写出来就成了下面的很麻烦的一段:

select A.month,A.country,trans_count,approved_count,trans_total_amount,approved_total_amount from 
(select date_format(trans_date,"%Y-%m") month,country,count(*) approved_count,sum(amount) approved_total_amount from Transactions
where state="approved"
group by country,date_format(trans_date,"%Y-%m")) A,
(select date_format(trans_date,"%Y-%m") month,country,count(*) trans_count,sum(amount) trans_total_amount from Transactions
group by country,date_format(trans_date,"%Y-%m")) B
where A.month=B.month and A.country=B.country

但是会有一些问题,就是如果记录是0条的话,coun(*)是不显示的,如果原始表没有approved的话,下面这段就会失效

select date_format(trans_date,"%Y-%m") month,country,count(*) approved_count,sum(amount) approved_total_amount from Transactions
where state="approved"
group by country,date_format(trans_date,"%Y-%m")

看了下讨论区的答案,group by本来就是一种条件筛选,然后作者又在聚合函数里面用条件筛选。

sum(state='approved') approved_count,

sum(case when state='approved' then amount else 0 end) approved_total_amount

select date_format(trans_date,"%Y-%m") as month, country, count(*) trans_count,
sum(state='approved') approved_count, 
sum(amount) trans_total_amount, 
sum(case when state='approved' then amount else 0 end) approved_total_amount
from transactions
group by country, date_format(trans_date,"%Y-%m")

 

order by convert(varchar(7),trans_date,120),country
group by substring(trans_date,1,7),country;
group by format(trans_date,'yyyy-MM'), country
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值