题目描述

(通过次数12,065 | 提交次数19,849,通过率60.78%)

Table: Transactions
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| country       | varchar |
| state         | enum    |
| amount        | int     |
| trans_date    | date    |
+---------------+---------+
id 是这个表的主键。
该表包含有关传入事务的信息。
state 列类型为 “[”批准“,”拒绝“] 之一。

编写一个 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                  |
+----------+---------+-------------+----------------+--------------------+-----------------------+

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/monthly-transactions-i
//测试数据
Create table If Not Exists Transactions (id int, country varchar(4), state enum('approved', 'declined'), amount int, trans_date date);

insert into Transactions (id, country, state, amount, trans_date) values ('121', 'US', 'approved', '1000', '2018-12-18');
insert into Transactions (id, country, state, amount, trans_date) values ('122', 'US', 'declined', '2000', '2018-12-19');
insert into Transactions (id, country, state, amount, trans_date) values ('123', 'US', 'approved', '2000', '2019-01-01');
insert into Transactions (id, country, state, amount, trans_date) values ('124', 'DE', 'approved', '2000', '2019-01-07');

解题思路

这道题比较简单,总的来说,直接按题目要求的维度进行汇总统计即可。
只是题目要求的维度无法从表中直接获取。
一方面,需要将date类型的trans_date字段转换为年月格式。可以使用date_format日期格式化函数。
另外,除了统计全部数据外,还需要统计仅审批通过的数据。在汇总统计时,可以通过CASE WHEN条件,过滤出审批通过的记录,然后进行COUNT和SUM。最终返回题目要求的结果。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    date_format(trans_date,'%Y-%m') month,
    country,
    count(1) 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
group by date_format(trans_date,'%Y-%m'),country;

picture loss