-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinal_Account_Balance.SQL
More file actions
37 lines (33 loc) · 921 Bytes
/
Final_Account_Balance.SQL
File metadata and controls
37 lines (33 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
--Final Account Balance
Given a table of bank deposits and withdrawals, return the final balance for each account.
Assumption:
All the transactions performed for each account are present in the table; no transactions are missing.
transactions Table:
Column Name Type
transaction_id integer
account_id integer
transaction_type varchar
amount decimal
transactions Example Input:
transaction_id account_id transaction_type amount
123 101 Deposit 10.00
124 101 Deposit 20.00
125 101 Withdrawal 5.00
126 201 Deposit 20.00
128 201 Withdrawal 10.00
Example Output:
account_id final_balance
101 25.00
201 10.00
Explanation:
In total, $30.00 were deposited to account 101, and $5.00 were withdrawn. Therefore, the final balance will be $30.00-$5.00 = $25.00
-- Solution
SELECT ACCOUNT_ID,
SUM(
CASE
WHEN TRANSACTION_TYPE = 'Deposit' THEN AMOUNT
ELSE -AMOUNT
END
) AS FINAL_BALANCE
FROM transactions
group by ACCOUNT_ID