Account Balance Calculation
Beginner Mode
Objective
Write a SQL query to calculate the final account balance for each account based on all transactions.
Table Schema:
- transactions
| Column | Type | Description |
|---|---|---|
| transaction_id | INTEGER | Unique identifier for each transaction |
| account_id | INTEGER | ID of the account |
| transaction_type | VARCHAR | Type of transaction ('deposit' or 'withdrawal') |
| amount | DECIMAL | Transaction amount |
Task Requirements:
- Process all transactions for each account
- Add deposits and subtract withdrawals
- Calculate the final balance for each account
- Sort results by account ID in ascending order
Output columns: account_id, final_balance
Examples
Example 1:
Output:
Input:
| transactions | |||
|---|---|---|---|
| account_id | amount | transaction_id | transaction_type |
| 101 | 1000 | 1 | deposit |
| 101 | 200 | 2 | withdrawal |
| 102 | 500 | 3 | deposit |
| 101 | 300 | 4 | deposit |
| 102 | 100 | 5 | withdrawal |
| account_id | final_balance |
|---|---|
| 101 | 1100 |
| 102 | 400 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
PayPal