How to find an account balance in SQL?
Question:
You have a transaction_detail
table with a record for each transaction. The transaction type could be debit, credit or refund. You need to add an additional column to track account balance.
Write a SQL query to achieve the expected output.
Answer:
Let us create the test data first.
To get the desired result, you can use aggregate function sum
with window function to calculate the running total for each row in a window. But, we have not defined the window (i.e, partition by
is not defined to define the window) here. Had we have to calculate the account balance for each account, we would have defined the window as account. So this query just calculates the running total for all the records in the table.