|
| 1 | +-- Problem: |
| 2 | + |
| 3 | +/* |
| 4 | +Table: Transactions |
| 5 | +
|
| 6 | ++---------------+---------+ |
| 7 | +| Column Name | Type | |
| 8 | ++---------------+---------+ |
| 9 | +| id | int | |
| 10 | +| country | varchar | |
| 11 | +| state | enum | |
| 12 | +| amount | int | |
| 13 | +| trans_date | date | |
| 14 | ++---------------+---------+ |
| 15 | +id is the primary key of this table. |
| 16 | +The table has information about incoming transactions. |
| 17 | +The state column is an enum of type ["approved", "declined"]. |
| 18 | + |
| 19 | +
|
| 20 | +Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount. |
| 21 | +
|
| 22 | +Return the result table in any order. |
| 23 | +
|
| 24 | +The query result format is in the following example. |
| 25 | +
|
| 26 | + |
| 27 | +
|
| 28 | +Example 1: |
| 29 | +
|
| 30 | +Input: |
| 31 | +Transactions table: |
| 32 | ++------+---------+----------+--------+------------+ |
| 33 | +| id | country | state | amount | trans_date | |
| 34 | ++------+---------+----------+--------+------------+ |
| 35 | +| 121 | US | approved | 1000 | 2018-12-18 | |
| 36 | +| 122 | US | declined | 2000 | 2018-12-19 | |
| 37 | +| 123 | US | approved | 2000 | 2019-01-01 | |
| 38 | +| 124 | DE | approved | 2000 | 2019-01-07 | |
| 39 | ++------+---------+----------+--------+------------+ |
| 40 | +Output: |
| 41 | ++----------+---------+-------------+----------------+--------------------+-----------------------+ |
| 42 | +| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount | |
| 43 | ++----------+---------+-------------+----------------+--------------------+-----------------------+ |
| 44 | +| 2018-12 | US | 2 | 1 | 3000 | 1000 | |
| 45 | +| 2019-01 | US | 1 | 1 | 2000 | 2000 | |
| 46 | +| 2019-01 | DE | 1 | 1 | 2000 | 2000 | |
| 47 | ++----------+---------+-------------+----------------+--------------------+-----------------------+` |
| 48 | +*/ |
| 49 | + |
| 50 | +------------------------------------------------------------------------------- |
| 51 | + |
| 52 | +-- Solution: |
| 53 | + |
1 | 54 | SELECT
|
2 | 55 | DATE_FORMAT(trans_date, "%Y-%m") AS month,
|
3 | 56 | country,
|
|
0 commit comments