【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
相关推荐
Cikiss15 分钟前
微服务实战——平台属性
java·数据库·后端·微服务
小小不董29 分钟前
《Linux从小白到高手》理论篇:深入理解Linux的网络管理
linux·运维·服务器·数据库·php·dba
无敌少年小旋风1 小时前
MySQL 内部优化特性:索引下推
数据库·mysql
柒小毓1 小时前
将excel导入SQL数据库
数据库
bug菌¹1 小时前
滚雪球学Oracle[2.5讲]:数据库初始化配置
数据库·oracle·数据库初始化·初始化配置
一休哥助手1 小时前
Redis 五种数据类型及底层数据结构详解
数据结构·数据库·redis
翔云1234561 小时前
MVCC(多版本并发控制)
数据库·mysql
夜雨翦春韭2 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
代码敲上天.2 小时前
数据库语句优化
android·数据库·adb
一直学习永不止步2 小时前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序