【LeetCode】1193. 每月交易 I

表:Transactions

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| country       | varchar |
| state         | enum    |
| amount        | int     |
| trans_date    | date    |
+---------------+---------+
id 是这个表的主键。
该表包含有关传入事务的信息。
state 列类型为 ["approved", "declined"] 之一

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

任意顺序 返回结果表。

查询结果格式如下所示。

复制代码
 
输入:
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                  |
+----------+---------+-------------+----------------+--------------------+-----------------------+
sql 复制代码
with cte1 as(
  select
  Transactions.*,
  DATE_FORMAT(trans_date,'%Y-%m') as 'month'
  from
  Transactions
),
cte2 as(
  select cte1.month,country,
  ifnull(count(1),0) as trans_count,
  ifnull(sum(amount),0) as trans_total_amount
  from cte1
  group by cte1.month,country
),
cte3 as(
  select cte1.month,country,
  ifnull(count(1),0) as approved_count,
  ifnull(sum(amount),0) as approved_total_amount
  from cte1
  where state='approved'
  group by cte1.month,country
)

select cte2.month,cte2.country,
trans_count,
ifnull(approved_count,0) as approved_count,
trans_total_amount,
ifnull(approved_total_amount,0) as approved_total_amount
from cte2 left join cte3
on cte2.month=cte3.month and cte2.country=cte3.country
相关推荐
Sylvia33.12 分钟前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
ruleslol42 分钟前
Mybatis11-不同的数据库连接池的配置
数据库·mybatis
苏州邦恩精密1 小时前
蔡司3D扫描仪厂家如何应用于航空航天制造
大数据·数据库·人工智能·3d·自动化·制造
alxraves1 小时前
医院远程会诊系统:数据库模块设计与实现
数据库·oracle
wordpress资料库1 小时前
WordPress数据表前缀的修改方法(完整版)
数据库·wordpress数据表前缀·wordpress修改前缀
退休倒计时2 小时前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
苦瓜汤补钙2 小时前
Oracle JDK8 环境配置-Win11
开发语言·数据库·笔记·oracle
Dovis(誓平步青云)2 小时前
《 AI直连数据库落地实践:基于MCP协议打通开发工具与数据库全链路运维分析》
大数据·linux·运维·数据库·人工智能·架构
一缕清烟在人间2 小时前
鸿蒙应用开发实战【27】— DatabaseService 数据库初始化
javascript·数据库·harmonyos·鸿蒙系统
G.O.G.O.G2 小时前
《LeetCode SQL 从入门到精通(MySQL)》09
sql·mysql·leetcode