A transactions table records every deposit and withdrawal made on an account. Write a SQL query to calculate the current balance of every account: the sum of its deposits minus the sum of its withdrawals. Return account_id and balance, ordered by account_id ascending.
Input Table(s)
Table transactions
| Column | Type | Meaning |
|---|
transaction_id | INT | Transaction id |
account_id | INT | Account the transaction belongs to (NOT NULL) |
transaction_type | VARCHAR(20) | 'deposit' or 'withdrawal' (NOT NULL) |
amount | DECIMAL(10,2) | Transaction amount, always positive (NOT NULL) |
transaction_date | DATE | Date of the transaction (NOT NULL) |
Primary key: transaction_id. There is no separate accounts table.
Output Contract
-
Columns, in this order:
account_id
,
balance
.
-
One row per distinct
account_id
in
transactions
.
-
balance
is the sum of deposit amounts minus the sum of withdrawal amounts, kept as a decimal with two places and no other rounding. It can be zero or negative.
-
Rows ordered by
account_id
ascending. Each
account_id
appears once in the output, so the order is unique.
Example
Input transactions:
| transaction_id | account_id | transaction_type | amount | transaction_date |
|---|
| 1 | 201 | deposit | 250.00 | 2024-02-01 |
| 2 | 201 | withdrawal | 250.00 | 2024-02-05 |
| 3 | 202 | withdrawal | 50.00 | 2024-02-03 |
Expected output:
| account_id | balance |
|---|
| 201 | 0.00 |
| 202 | -50.00 |
Account 201 deposited 250 and withdrew 250, resulting in a balance of 0. Account 202 only has a withdrawal of 50, so the balance is -50.
Constraints and Clarifications
-
The number of rows in
transactions
is between 1 and 10,000.
-
transaction_type
is either
'deposit'
or
'withdrawal'
.
-
amount
is a positive decimal value.
-
Each
transaction_id
is unique, and no column is ever
NULL
.
-
Two rows with the same account, type, amount and date are separate transactions, and both count.
-
transaction_date
does not filter anything: the balance covers every row of the account.
-
A negative balance is reported as it is.