本文主要是介绍【MySQL】group by 之后 having 后面直接加字段的写法可以忽略为零的行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
力扣题
1、题目地址
1205. 每月交易 II
2、模拟表
Transactions 记录表:
Column Name | Type |
---|---|
id | int |
country | varchar |
state | enum |
amount | int |
trans_date | date |
- id 是这个表的主键。
- 该表包含有关传入事务的信息。
- 状态列是枚举类型,值为 [approved、declined] 其中之一的列。
Chargebacks 表:
Column Name | Type |
---|---|
trans_id | int |
trans_date | date |
- 退单包含有关放置在事务表中的某些事务的传入退单的基本信息。
- trans_id 是 transactions 表的 id 列的外键(reference 列)。
- 每项退单都对应于之前进行的交易,即使未经批准。
3、要求
编写一个解决方案,找出每个国家/地区的每月交易信息:已批准交易的数量及其总金额、退单的数量及其总金额。
注意:在你的解决方案中,只需显示给定月份和国家,忽略所有为零的行。
以 任意顺序 返回结果表。
4、示例
输入:
Transactions 表:
id | country | state | amount | trans_date |
---|---|---|---|---|
101 | US | approved | 1000 | 2019-05-18 |
102 | US | declined | 2000 | 2019-05-19 |
103 | US | approved | 3000 | 2019-06-10 |
104 | US | declined | 4000 | 2019-06-13 |
105 | US | approved | 5000 | 2019-06-15 |
Chargebacks 表:
trans_id | trans_date |
---|---|
102 | 2019-05-29 |
101 | 2019-06-30 |
105 | 2019-09-18 |
输出:
month | country | approved_count | approved_amount | chargeback_count | chargeback_amount |
---|---|---|---|---|---|
2019-05 | US | 1 | 1000 | 1 | 2000 |
2019-06 | US | 2 | 8000 | 1 | 1000 |
2019-09 | US | 0 | 0 | 1 | 5000 |
5、代码编写
网友写法
with tmp as (select * from Transactionsunion allselect two.id, two.country, 'chargeback', two.amount, one.trans_datefrom Chargebacks oneleft join Transactions two on one.trans_id = two.id
)
select date_format(trans_date, '%Y-%m') AS month,country,sum(state = 'approved') 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 tmp
group by month, country
having approved_amount or chargeback_amount
上面 sql 中 having 后面直接加字段的用法和我写的一篇文章类似
简单来说就是省略比较符的写法
having approved_amount or chargeback_amount
等同于 having approved_amount > 0 or chargeback_amount > 0
【MySQL】GROUP BY 后用 HAVING 进行筛选(筛选使用 SUM(条件表达式) 的语法,且不加比较符的写法)
上面 sql 中 sum 函数用法可参考
【MySQL】sum 函数和 count 函数的相同作用
这篇关于【MySQL】group by 之后 having 后面直接加字段的写法可以忽略为零的行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!