问题
Is that possible to avoid negative balance using MySql query? I have the following MySql table:
trx_no trx_date Opening debit credit 1 2019-10-01 200 0 100 2 2019-10-02 200 0 100 3 2019-10-03 200 100 0 4 2019-10-03 200 400 0 5 2019-10-03 200 0 200 6 2019-10-04 200 0 100 7 2019-10-05 200 0 400
with this query:
SELECT
trx_no,
trx_date,
Opening,
debit,
credit,
Opening + (SELECT SUM(t2.credit - t2.debit)
FROM MyTable t2
WHERE t2.trx_no <= t1.trx_no) AS balance
FROM MyTable t1
ORDER BY
trx_no;
I got:
trx_no trx_date Opening debit credit balance
1 2019-10-01 200 0 100 300
2 2019-10-02 200 0 100 400
3 2019-10-03 200 100 0 300
4 2019-10-03 200 400 0 -100
5 2019-10-03 200 0 200 100
6 2019-10-04 200 0 100 200
7 2019-10-05 200 0 400 600
You can see that there is a negative balance (-100) on 2019-10-03. Is that possible to make a mysql query to avoid negative balance by allowing credit calculation first if there are debit and credit on the same date? so the result will become:
trx_no trx_date Opening debit credit balance
1 2019-10-01 200 0 100 300
2 2019-10-02 200 0 100 400
5 2019-10-03 200 0 200 600
3 2019-10-03 200 100 0 500
4 2019-10-03 200 400 0 100
6 2019-10-04 200 0 100 200
7 2019-10-05 200 0 400 600
DB Fiddle
回答1:
The condition:
WHERE t2.trx_no <= t1.trx_no
does not work in your case.
You need the rows ordered by trx_date
, then by credits first and then debits and finally by trx_no
.
This code will use a combined column (with concatenation) of these 3 conditions:
SELECT
t1.trx_no,
t1.trx_date,
t1.Opening,
t1.debit,
t1.credit,
t1.Opening + (
SELECT SUM(t2.credit - t2.debit)
FROM MyTable t2
WHERE
concat(t2.trx_date, t2.debit > t2.credit, lpad(t2.trx_no, 10, '0')) <=
concat(t1.trx_date, t1.debit > t1.credit, lpad(t1.trx_no, 10, '0'))
) AS balance
FROM MyTable t1
ORDER BY concat(t1.trx_date, t1.debit > t1.credit, lpad(t1.trx_no, 10, '0'))
See the demo.
Results:
| trx_no | trx_date | Opening | debit | credit | balance |
| ------ | ---------- | ------- | ----- | ------ | ------- |
| 1 | 2019-10-01 | 200 | 0 | 100 | 300 |
| 2 | 2019-10-02 | 200 | 0 | 100 | 400 |
| 5 | 2019-10-03 | 200 | 0 | 200 | 600 |
| 3 | 2019-10-03 | 200 | 100 | 0 | 500 |
| 4 | 2019-10-03 | 200 | 400 | 0 | 100 |
| 6 | 2019-10-04 | 200 | 0 | 100 | 200 |
| 7 | 2019-10-05 | 200 | 0 | 400 | 600 |
来源:https://stackoverflow.com/questions/58451767/mysql-query-to-avoiding-negative-balance