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 

比较简单就这样吧

相关推荐
舞影天上6 分钟前
RuoYi-Vue-Plus Docker 部署踩坑:MySQL 中文双重编码的根因与修复
数据库
卡提西亚9 分钟前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结21 分钟前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
Wzx1980121 小时前
Redis&ES——Retriever的抽象实现
数据库·人工智能·redis·elasticsearch
G.O.G.O.G1 小时前
《LeetCode SQL 从入门到进阶(MySQL)》06(下)
数据库·sql·oracle
heimeiyingwang1 小时前
【架构实战】SQL注入与XSS防御:常见Web漏洞的系统性修复
前端·sql·架构
zandy10112 小时前
多租户SaaS架构下的BI数据隔离与权限治理体系
数据库·架构·数据加密
多巴胺梦想家2 小时前
NoSQL 数据库:不只是关系型
数据库·nosql
数字孪生家族3 小时前
3DGS 数据编辑单体化技术:将高斯重建转化为结构化数字空间资产
数据库·3d·高斯泼溅·空间智能应用
广州灵眸科技有限公司3 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) 系统操作-线进程操作
数据库·单片机·嵌入式硬件·算法·php