Monthly Transactions I Problem


Description

LeetCode Problem 1193.

Table: Transactions

1
2
3
4
5
6
7
8
9
10
11
12
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| country       | varchar |
| state         | enum    |
| amount        | int     |
| trans_date    | date    |
+---------------+---------+
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enum of type ["approved", "declined"].

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.

The query result format is in the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 |
+------+---------+----------+--------+------------+

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                  |
+----------+---------+-------------+----------------+--------------------+-----------------------+


MySQL Solution

1
2
3
4
5
6
7
select date_format(trans_date,"%Y-%m") as month, country, 
    count(id) as trans_count,
    sum(case when state='approved' then 1  else 0 end) as approved_count,
    sum(amount) as trans_total_amount,
    sum(case when state='approved' then amount  else 0 end) as approved_total_amount
from transactions
group by month, country




Related Posts

Tournament Winners Problem

LeetCode 1194. Write an SQL query to find the winner...

Immediate Food Delivery II Problem

LeetCode 1174. Write an SQL query to find the percentage...

Product Price At A Given Date Problem

LeetCode 1164. Write an SQL query to find the prices...

Monthly Transactions I Problem

LeetCode 1193. Write an SQL query to find for each...

Reformat Department Table Problem

LeetCode 1179. Write an SQL query to reformat the table...

Immediate Food Delivery I Problem

LeetCode 1173. Write an SQL query to find the percentage...