MySql避免负余额的查询

MySql Query to Avoiding Negative Balance

是否可以使用 MySql 查询来避免负余额? 我有以下 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      

使用此查询:

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;

我得到了:

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

可以看到2019-10-03出现负余额(-100)。 是否可以通过首先允许贷方计算来进行mysql查询以避免负余额如果在同一日期有借方和贷方?所以结果会变成:

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

条件:

WHERE t2.trx_no <= t1.trx_no

不适用于您的情况。
您需要按 trx_date 排序的行,然后先按贷方,然后按借方,最后按 trx_no.
此代码将使用这 3 个条件的组合列(串联):

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'))

参见demo
结果:

| 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     |