建表语句:
Create table If Not Exists Transactions (id int, country varchar(4), state enum('approved', 'declined'), amount int, trans_date date)
Truncate table Transactions
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')
表: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 |
+----------+---------+-------------+----------------+--------------------+-----------------------+
解题思路:
按时找输出的内容去做题
month 截取了 年月 我们使用 date_fromat 函数
country,直出
trans_count 是在统计申请次数 COUNT函数
approved_count 通过的函数 可以使用 COUNT IF 也可以使用 SUM()来统计
trans_total_amount 申请的金额 包含没通过的 使用 sun()聚合函数
approved_total_amount 统计申请通过的金额 使用 sun(if()))
select DATE_FORMAT(trans_date,'%Y-%m') as month,country,
count(*) as trans_count,
sum(state='approved') 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;
总结:今天学习到了group by规则
ONLY_FULL_GROUP_BY
模式规则
规则 1:非聚合列必须出现在 GROUP BY
子句中
任何非聚合列(比如原始字段、格式化后的字段、计算列等)如果要出现在 SELECT
中,必须包含在 GROUP BY
子句中。
示例:
SELECT column1, column2, COUNT(*)
FROM table
GROUP BY column1, column2;
规则 2:非聚合列必须是 GROUP BY
列的函数依赖
任何非聚合列(比如原始字段、格式化后的字段、计算列等)如果要出现在 SELECT
中,必须包含在 GROUP BY
子句中。
示例:
SELECT column1, column2, COUNT(*)
FROM table
GROUP BY column1, column2;