【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
相关推荐
艾莉丝努力练剑30 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
StarRocks_labs2 小时前
StarRocks Community Monthly Newsletter (Jun)
数据库·starrocks·数据湖·物化视图·存算分离
光电的一只菜鸡3 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
ob熔天使——武4 小时前
MySQL
数据库·mysql
小光学长4 小时前
基于vue框架的防疫物资仓库管理系统09y38(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
野生技术架构师8 小时前
MySQL数据实时同步到Elasticsearch的高效解决方案
数据库·mysql·elasticsearch
白仑色8 小时前
Oracle 高可用性与安全性
数据库·oracle·数据安全·goldengate·高可用架构
紫无之紫9 小时前
SQL性能调优经验总结
数据库·sql·性能调优
CZZDg9 小时前
Redis Sentinel哨兵集群
java·网络·数据库