【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
相关推荐
阿巴~阿巴~24 分钟前
Centos 7/8 安装 Redis
linux·服务器·数据库·redis·centos
刘大猫.25 分钟前
mysql数据库压缩
数据库·mysql·压缩·mysql数据库压缩·数据库压缩·数据库备份与压缩
oracle040630 分钟前
sql练习题单-知识点总结
数据库·sql
会飞的架狗师30 分钟前
【MySQL体系】第4篇:MySQL 查询优化实用技巧
数据库·mysql
lypzcgf1 小时前
Coze源码分析-资源库-编辑数据库-前端源码-核心组件
前端·数据库·源码分析·coze·coze源码分析·ai应用平台·agent平台
wei_shuo1 小时前
KingbaseES聚焦产品上线
数据库·kingbasees
难以触及的高度1 小时前
Linux-CentOS 7 上安装 MySQL 8.0.43(保姆级教程)
linux·mysql·centos
AI浩1 小时前
Redis中的RPOP、BRPOP、LPOP 和 BLPOP
数据库·chrome·redis
数据和云2 小时前
从Databricks和Supabase看AI时代的中国数据库启示
数据库·人工智能
我科绝伦(Huanhuan Zhou)2 小时前
Oracle ADRCI工具全面使用指南:从基础到故障诊断实战
数据库·oracle