1193. Monthly Transactions I
Problem Statement
Table: Transactions
Column Name | Type |
---|---|
id | int |
country | varchar |
state | enum |
amount | int |
trans_date | date |
The
id
column is the primary key column for this table.The table has information about incoming transactions.
The
state
column is an enum of type ["approved", "declined"].
Instructions
- 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.
- Return the result table in any order.
- The query result format is in the following example.
Example
Input: 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 |
Output:
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 |
Submissions
sql
WITH MonthlyTransactions AS (
SELECT
TO_CHAR(trans_date, 'YYYY-MM') AS month,
country,
state,
amount
FROM
Transactions
)
SELECT
month,
country,
COUNT(*) 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
MonthlyTransactions
GROUP BY
month, country;
Explanations
PostgreSQL
Submitted by @noeyislearning
WITH MonthlyTransactions AS (...)
: Create a Common Table Expression (CTE) namedMonthlyTransactions
that selects themonth
,country
,state
, andamount
columns from theTransactions
table.SELECT TO_CHAR(trans_data, 'YYYY-MM') AS month
: Extract the year and month from thetrans_date
column and format it asYYYY-MM
.country
: Select thecountry
column.state
: Select thestate
column.amount
: Select theamount
column.
FROM Transactions
: Select theTransactions
table.
SELECT ...
: Select the following columns:month
: Select themonth
column.country
: Select thecountry
column.COUNT(*) AS trans_count
: Count the number of transactions and alias it astrans_count
.SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count
: Sum the number of approved transactions and alias it asapproved_count
.SUM(amount) AS trans_total_amount
: Sum the total amount of transactions and alias it astrans_total_amount
.SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) AS approved_total_amount
: Sum the total amount of approved transactions and alias it asapproved_total_amount
.
FROM MonthlyTransactions
: Select theMonthlyTransactions
CTE.GROUP BY month, country
: Group the result bymonth
andcountry
.