SQL-leetcode—1193. 每月交易 I

1193. 每月交易 I

表:Transactions

±--------------±--------+

| Column Name | Type |

±--------------±--------+

| id | int |

| country | varchar |

| state | enum |

| amount | int |

| trans_date | date |

±--------------±--------+

id 是这个表的主键。

该表包含有关传入事务的信息。

state 列类型为 ["approved", "declined"] 之一。

编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

以 任意顺序 返回结果表。

查询结果格式如下所示。

示例 1:

输入:

Transactions table:

±-----±--------±---------±-------±-----------+

| id | country | state | amount | trans_date |

±-----±--------±---------±-------±-----------+

| 121 | US | approved | 1000 | 2018-12-18 |

| 122 | US | declined | 2000 | 2018-12-19 |

| 123 | US | approved | 2000 | 2019-01-01 |

| 124 | DE | approved | 2000 | 2019-01-07 |

±-----±--------±---------±-------±-----------+

输出:

±---------±--------±------------±---------------±-------------------±----------------------+

| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |

±---------±--------±------------±---------------±-------------------±----------------------+

| 2018-12 | US | 2 | 1 | 3000 | 1000 |

| 2019-01 | US | 1 | 1 | 2000 | 2000 |

| 2019-01 | DE | 1 | 1 | 2000 | 2000 |

±---------±--------±------------±---------------±-------------------±----------------------+

题解

查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

  • 查找每个月和每个国家/地区的 -- group by
  • 事务数及其总金额、已批准的事务数及其总金额 -- 有条件的聚合

方法一: date_format + group by + 聚合函数

复制代码
select
    date_format(trans_date,'%Y-%m') as month
    ,country
    ,count(id) as trans_count
    ,sum(if(state='approved',1,0)) as approved_count
    ,sum(amount) as trans_total_amount
    ,sum(if(state='approved',amount,0)) as approved_total_amount
from Transactions
group by country,date_format(trans_date,'%Y-%m')

方法二:left + group by + 聚合函数

复制代码
select left(trans_date ,7) month
,country 
,count(state) trans_count 
,count(case when state = 'approved' then '1' else null end) approved_count
,sum(amount )trans_total_amount
,sum(case when state = 'approved' then amount else '0' end)approved_total_amount
 from Transactions a  group by left(trans_date ,7),country 

比较简单就这样吧

相关推荐
数据库小组4 小时前
2026 年,MySQL 到 SelectDB 同步为何更关注实时、可观测与可校验?
数据库·mysql·数据库管理工具·数据同步·ninedata·selectdb·迁移工具
华科易迅4 小时前
MybatisPlus增删改查操作
android·java·数据库
Kethy__4 小时前
计算机中级-数据库系统工程师-计算机体系结构与存储系统
大数据·数据库·数据库系统工程师·计算机中级
SHoM SSER4 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
米粒15 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
熬夜的咕噜猫5 小时前
MySQL备份与恢复
数据库·oracle
jnrjian5 小时前
recover database using backup controlfile until cancel 假recover,真一致
数据库·oracle
lifewange6 小时前
java连接Mysql数据库
java·数据库·mysql
Mr_Xuhhh6 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
大妮哟6 小时前
postgresql数据库日志量异常原因排查
数据库·postgresql·oracle