简体   繁体   中英

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:
  • ID
  • Customer_ID
  • Date
  • Credit
  • Debit and
  • Balance (Calculated)

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

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM