题目
表: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(具体语句将写在知识积累)。
- 在Transactions表根据trans_date的月和country做group by。
- 选择的属性(方法):month(通过date_format(date, '%Y-%m')提取月份信息),country,trans_count(count交易数据数),approved_count(count在state=‘approved’的交易数据数),trans_total_amount(sum交易的amount),approved_total_amount(sum在state=‘approved’的交易数据数)。
代码实现
# Write your MySQL query statement below
select date_format(trans_date,'%Y-%m') as month, country, count(*) as trans_count, count(if(state='approved',1,null)) as approved_count, sum(amount) as trans_total_amount, sum(if(state='approved',amount,0)) as approved_total_amount
from Transactions
group by date_format(trans_date,'%Y-%m'), country
知识积累
- 日期格式:%Y-%m-%d
- 控制并提取某精确度的日期信息:date_formate(date, format)通过format控制date的提取的精确度,format的格式是日期格式。