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 

比较简单就这样吧

相关推荐
码士集团小青11 分钟前
面霸篇:高频 Java 基础问题(核心卷一)
linux·服务器·数据库·redis·缓存·1024程序员节
hold?fish:palm1 小时前
40 二叉树的直径
c++·leetcode
LMT流氓兔1 小时前
第五单元——第十二课:把脚本整理成项目
java·数据库·python·langchain·1024程序员节
cuijiecheng20181 小时前
WeFlow 无法使用怎么办?一次数据库组件到期问题的排查与修复
数据库·oracle
guo_wen_qiang2 小时前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节
一条泥憨鱼2 小时前
【Redis | 黑马点评】附近商铺功能源码解读
数据库·redis·缓存
爱读书的小胖2 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
念何架构之路3 小时前
Go reflect 包:结构体反射 —Field、Tag 与 VisibleFields
java·数据库·golang
EnCi Zheng3 小时前
PostgreSQL 实战指南:安装配置、数据类型、索引选型、MVCC 事务与高可用备份全解析
数据库·sql·postgresql·索引·1024程序员节
Navigator_Z4 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode