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 

比较简单就这样吧

相关推荐
m0_59674909几秒前
C#怎么使用with表达式 C#record类型中with表达式怎么用如何创建对象的修改副本【语法】
jvm·数据库·python
尚雷55802 分钟前
Oracle 多租户架构下常用运维SQL
数据库·sql·oracle
神明9313 分钟前
uni-app动画效果实现 uni-app如何使用animation API
jvm·数据库·python
m0_690825823 分钟前
uni-app怎么做类似于微博的新消息气泡 uni-app角标动画效果实现【代码】
jvm·数据库·python
m0_631529824 分钟前
uni-app iOS后台运行 uni-app App如何实现后台定位或音乐播放
jvm·数据库·python
Mike117.5 分钟前
GBase 8c 序列用在业务流水号上要留几道边界
服务器·数据库
2301_779622415 分钟前
如何睡眠等待_DBMS_LOCK.SLEEP与DBMS_SESSION暂停当前会话
jvm·数据库·python
2303_821287387 分钟前
CSS中如何实现绝对定位元素的等比缩放_利用宽高百分比
jvm·数据库·python
java修仙传10 分钟前
实习日志:完成算法调用总接口并修复联调问题
java·开发语言·数据库
OceanBase数据库官方博客10 分钟前
你的数据库是否为 Agent 准备好?
数据库·oracle