Monthly Transactions I - Problem
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 Transactions table contains:
id- Primary keycountry- Transaction countrystate- Either 'approved' or 'declined'amount- Transaction amounttrans_date- Transaction date
Return the result table in any order.
Table Schema
Transactions
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key |
country
|
varchar | Country where transaction occurred |
state
|
enum | Transaction state: 'approved' or 'declined' |
amount
|
int | Transaction amount |
trans_date
|
date | Date when transaction occurred |
Primary Key: id
Note: Each row represents one transaction with approval status
Input & Output
Example 1 — Mixed Approved and Declined Transactions
Input 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 | trans_total_amount | approved_count | approved_total_amount |
|---|---|---|---|---|---|
| 2018-12 | US | 2 | 3000 | 1 | 1000 |
| 2019-01 | DE | 1 | 2000 | 1 | 2000 |
| 2019-01 | US | 1 | 2000 | 1 | 2000 |
💡 Note:
Groups transactions by month and country. For US in 2018-12: 2 total transactions (1 approved, 1 declined) with total amount 3000 and approved amount 1000.
Example 2 — All Declined Transactions
Input Table:
| id | country | state | amount | trans_date |
|---|---|---|---|---|
| 125 | CA | declined | 1500 | 2019-02-15 |
| 126 | CA | declined | 500 | 2019-02-20 |
Output:
| month | country | trans_count | trans_total_amount | approved_count | approved_total_amount |
|---|---|---|---|---|---|
| 2019-02 | CA | 2 | 2000 | 0 | 0 |
💡 Note:
When all transactions are declined, approved_count and approved_total_amount are both 0, while trans_count and trans_total_amount include all transactions.
Constraints
-
1 ≤ id ≤ 1000 -
stateis either'approved'or'declined' -
countrycontains only uppercase letters -
1 ≤ amount ≤ 10000
Visualization
Tap to expand
Understanding the Visualization
1
Input Data
Individual transactions with dates and states
2
Group & Aggregate
GROUP BY month/country, conditional SUM
3
Monthly Summary
Aggregated transaction metrics per month-country
Key Takeaway
🎯 Key Insight: Use conditional aggregation with CASE WHEN to calculate multiple metrics (all vs approved) in a single GROUP BY query
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code