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 

比较简单就这样吧

相关推荐
小小程序员.¥2 分钟前
oracle--函数
数据库·sql·mysql
Leon-Ning Liu2 分钟前
Oracle 26ai 新特性: True Cache(真实缓存)
数据库·缓存·oracle
Leon-Ning Liu3 分钟前
Oracle 26ai 的 SQL 语言增强特性
数据库·sql·oracle
Elastic 中国社区官方博客4 分钟前
Elasticsearch:语义搜索,现在默认支持多语言
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
小江的记录本4 分钟前
【JEECG Boot】 JEECG Boot 数据字典管理——六大核心功能(内含:《JEECG Boot 数据字典开发速查清单》)
java·前端·数据库·spring boot·后端·spring·mybatis
小年糕是糕手5 分钟前
【35天从0开始备战蓝桥杯 -- Day9】
数据结构·数据库·c++·算法·蓝桥杯
weixin_3077791310 分钟前
使用COPY INTO从S3导入CSV文件到Azure Synapse Dedicated SQL Pool表的问题分析与自动化验证方案
sql·自动化·azure
Austindatabases12 分钟前
SQLite需要初始化参数,怎么调优-- SQLite 五脏俱全系列 (1)
数据库·sqlite
NineData12 分钟前
NineData V5.0 产品发布会:让 AI 成为数据管理的驱动力,4 月 16 日!
数据库·人工智能·数据库管理工具·ninedata·数据库迁移工具·数据安全管理·权限管控
Fly Wine15 分钟前
Leetcode只二叉树中序遍历(python解法)
算法·leetcode·职场和发展