【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
相关推荐
Morwit5 分钟前
【力扣hot100】 70. 爬楼梯
c++·算法·leetcode·职场和发展
hutengyi9 分钟前
保姆级JavaWeb项目创建、部署、连接数据库(tomcat)
数据库·tomcat·firefox
wuyikeer11 分钟前
docker 安装 mysql
mysql·adb·docker
寰宇的行者15 分钟前
深入理解 Django 异步视图中的 `sync_to_async` 与协程
数据库·django
Tisfy16 分钟前
LeetCode 3474.字典序最小的生成字符串:暴力填充
算法·leetcode·字符串·题解
草莓熊Lotso17 分钟前
MySQL 索引特性与性能优化全解
android·运维·数据库·c++·mysql·性能优化
大龄烤红薯18 分钟前
docker-【容器数据存储位置分析】以Mysql容器为例
mysql·adb·docker
薛定谔的悦22 分钟前
站控显示下级从控EMS的版本信息开发(设计多线程和TCP通讯)
linux·网络·数据库·网络协议·tcp/ip·ems
bcbobo21cn25 分钟前
C#使用一维数组作为参数传递
开发语言·数据库·c#·一维数组
老虎062725 分钟前
LeetCode热题100 刷题笔记(第五天)多维动态规划(中心扩展法) 「 最长回文子串」
笔记·leetcode·动态规划