SQL Interview Questions:4
4. 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.
create table transactions
(
transaction_id int,
account_id int,
transaction_type varchar(200),
amount decimal
)
insert into transactions values (123,101,'deposit',10.00),(124,101,'deposit',20.00),(125,101,'withdrawl',5.00),(126,201,'deposit',20.00),(128,201,'withdrawl',10.00)

select * from transactions
select account_id,sum( case when transaction_type='deposit' then +amount else -amount end )as final_balance from transactions group by account_id

Comments
Post a Comment