Skip to content
Advertisement

The sum of Opening and Closing Balances for each Financial Year Grouped by Category in MYSQL

I have used three days attempting how to figure out this with no avail.I also did some search even from this forum but failed too.
It might look like Duplicate Question but to be honest this is different from others has been asked.
My question is how to get the sum of Balance Carry forward C/F and Closing balance for each financial year being GROUPED BY loan_id For each Date Range ie.Financial year?


The above table schema and its data have mysql fiddle here
I have also read this thread MySQL Open Balance Credit Debit Balance which is only working for single user.

So far I have tried:

But the above is not giving correct results ,How do i get the results like these ones?
A: Query made for date between 2017-01-01 and 2018-12-31

B: Query made for date between 2019-01-01 and 2020-12-31

Advertisement

Answer

You are looking for conditional aggregation.

The key thing is that you need to start scanning the table from the beginning of the history in order to generate the initial balance. Then you just need to adjust the conditional sums:

Consider:

In your DB Fiddle, this returns:

And when changing the dates to 2020-2021:

NB: that was a well-asked question, that SO could use more of!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement