【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
相关推荐
旖旎夜光3 分钟前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
ZC跨境爬虫37 分钟前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
逐米时代1 小时前
智能招聘与人岗匹配:可解释匹配让录用依据有迹可循
大数据·数据库·人工智能
承渊政道1 小时前
KES专业技能包发布:覆盖数据库开发、迁移与运维全流程
运维·数据库·gitee·数据库开发·金仓数据库
IvorySQL1 小时前
PostgreSQL 日报| RI 快速路径并发读取缺陷(8 月 13 日)
数据库·postgresql
highreport2 小时前
HighReport报表工具定时调度和邮件定时发送
运维·服务器·数据库
01_ice2 小时前
数据库基础
数据库
deepdata_cn2 小时前
向量数据库是非结构化数据的AI检索底座
数据库·人工智能
梁辰兴2 小时前
软件工程:数据库设计
数据库·软件工程·数据库设计·逻辑设计·概念设计·梁辰兴·物理设计
10mAh3 小时前
【Git】误删分支、reset --hard 后提交丢了怎么办?——reflog、fsck 与安全恢复实战
数据库·git·安全·回归