Skip to content
Advertisement

MySQL Debit/Credit cumulative balance

I would like a cumulative DR or CR balance for the following table:

For the above table, a cumulative Balance column would be:

Decreasing a DR below 0 makes it a CR

Decreasing a CR below 0 makes it a DR

Where balance is 0, value is 0 DR It could be calculated as CR’s being a negative value, but I would like the ‘DR’ and ‘CR’ text to show in the balance column after an abs numerical value.

mysql Ver 14.14 Distrib 5.7.23, for Linux (x86_64) using EditLine wrapper

Thanks for your help

Advertisement

Answer

If you are running MySQL 8.0, you can use window functions:


In earlier versions, one efficient option uses a session variable:

Demo on DB Fiddle – both queries yield:

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