LeetCode:Database 65.每月交易 I
Posted Xiao Miao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 65.每月交易 I相关的知识,希望对你有一定的参考价值。
要求:编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。
Transactions 表的结构:
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| country | varchar |
| state | enum |
| amount | int |
| trans_date | date |
+---------------+---------+
id 是这个表的主键。
该表包含有关传入事务的信息。
state 列类型为 “[”批准“,”拒绝“] 之一。
Transactions 表:
+------+---------+----------+--------+------------+
| 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 |
+------+---------+----------+--------+------------+
Result Table:
+----------+---------+-------------+----------------+--------------------+-----------------------+
| 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 |
+----------+---------+-------------+----------------+--------------------+-----------------------+
SQL语法:
SELECT d1 AS month,c1 AS country,COUNT(i1) AS trans_count,
COUNT(i2) AS approved_count,SUM(a1) AS trans_total_amount,
ifnull(SUM(a2),0) AS approved_total_amount
FROM(
SELECT SUBSTR(a.trans_date,1,7) AS d1,a.country AS c1,a.id AS i1,b.id AS i2,a.amount AS a1,b.amount AS a2
FROM
Transactions a
LEFT JOIN Transactions b
ON a.id=b.id
AND b.state='approved')c
GROUP BY d1,c1;
以上是关于LeetCode:Database 65.每月交易 I的主要内容,如果未能解决你的问题,请参考以下文章