【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
相关推荐
阿蒙Amon2 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
互联网搬砖老肖6 小时前
运维打铁: MongoDB 数据库集群搭建与管理
运维·数据库·mongodb
典学长编程7 小时前
数据库Oracle从入门到精通!第四天(并发、锁、视图)
数据库·oracle
积跬步,慕至千里7 小时前
clickhouse数据库表和doris数据库表迁移starrocks数据库时建表注意事项总结
数据库·clickhouse
极限实验室8 小时前
搭建持久化的 INFINI Console 与 Easysearch 容器环境
数据库
星辰离彬8 小时前
Java 与 MySQL 性能优化:Java应用中MySQL慢SQL诊断与优化实战
java·后端·sql·mysql·性能优化
白仑色8 小时前
Oracle PL/SQL 编程基础详解(从块结构到游标操作)
数据库·oracle·数据库开发·存储过程·plsql编程
程序猿小D9 小时前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的个人财务管理系统,推荐!
java·数据库·mysql·spring·毕业论文·ssm框架·个人财务管理系统
钢铁男儿10 小时前
C# 接口(什么是接口)
java·数据库·c#
__风__11 小时前
PostgreSQL kv(jsonb)存储
数据库·postgresql