mysqlviewcalculationbank

how to create a MySql query to display running balance from credit and debit where multiple customers have indivdual balances


I have a table as with the structure below:

enter image description here

The Table is a simple credit and debit table for different customers ( each customer has his own ID).

Transactions take place on different dates. Each transaction has its own ID which is chronologically generated.

A view must be created as showing the running balance of each customer. The view gives the list chronologically arranged.

The list items are

  1. Transaction:

I would like to get the query code for solving the above problem. Thanking you in anticipation.


Solution

  • This should work

      select  transaction_id, customer_id, date, credit, debit,
      abs(sum(ifnull(credit,0)) over (partition by customer_id order by date,credit,transaction_id ) - sum(ifnull(debit,0)) over(partition by customer_id order by date,debit,transaction_id)) as balance
      from ledger
      order by transaction_id;