SQL-leetcode—1193. 每月交易 I

1193. 每月交易 I

表:Transactions

±--------------±--------+

| Column Name | Type |

±--------------±--------+

| id | int |

| country | varchar |

| state | enum |

| amount | int |

| trans_date | date |

±--------------±--------+

id 是这个表的主键。

该表包含有关传入事务的信息。

state 列类型为 ["approved", "declined"] 之一。

编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

以 任意顺序 返回结果表。

查询结果格式如下所示。

示例 1:

输入:

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 |

±---------±--------±------------±---------------±-------------------±----------------------+

题解

查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

  • 查找每个月和每个国家/地区的 -- group by
  • 事务数及其总金额、已批准的事务数及其总金额 -- 有条件的聚合

方法一: date_format + group by + 聚合函数

复制代码
select
    date_format(trans_date,'%Y-%m') as month
    ,country
    ,count(id) as trans_count
    ,sum(if(state='approved',1,0)) as approved_count
    ,sum(amount) as trans_total_amount
    ,sum(if(state='approved',amount,0)) as approved_total_amount
from Transactions
group by country,date_format(trans_date,'%Y-%m')

方法二:left + group by + 聚合函数

复制代码
select left(trans_date ,7) month
,country 
,count(state) trans_count 
,count(case when state = 'approved' then '1' else null end) approved_count
,sum(amount )trans_total_amount
,sum(case when state = 'approved' then amount else '0' end)approved_total_amount
 from Transactions a  group by left(trans_date ,7),country 

比较简单就这样吧

相关推荐
2401_882273722 分钟前
如何通过MongoDB GridFS实现文件的分块下载
jvm·数据库·python
weixin_580614002 分钟前
CSS如何实现动态背景色线性渐变_利用CSS变量控制渐变方向
jvm·数据库·python
施棠海4 分钟前
SQLite姓氏数据库首字母检索开发
数据库·oracle
weixin_408717774 分钟前
mysql如何查询所有列_mysql select星号性能分析
jvm·数据库·python
a9511416424 分钟前
mysql权限表查询性能如何优化_MySQL系统权限缓存原理
jvm·数据库·python
zxrhhm7 分钟前
Oracle RAC 日常监控脚本
数据库·oracle
m0_748920368 分钟前
Redis怎样防止主从节点淘汰行为不一致
jvm·数据库·python
misL NITL8 分钟前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
2401_835956819 分钟前
SQL中如何查找特定的空值行:WHERE IS NULL深度解析
jvm·数据库·python
若兰幽竹9 分钟前
【从零开始编写数据库系统:架构设计与实现】第3章 SQL解析:词法与语法分析
数据库·sql·教学数据库·数据库内核开发