我想得到每个借方和贷方的余额,然后计算每行的余额。。
SELECT SUM(IF(s.AMT>0 AND s.SLE_CODE=11,s.AMT,0)) AS DEBIT,
SUM(IF(s.AMT<0 AND s.SLE_CODE=11,s.AMT,0)) * -1 AS CREDIT
FROM
sldtl AS s
LEFT JOIN
transtype
ON
transtype.TransTypeID = s.TR_CODE
WHERE
s.SL_BRCODE= 1 AND s.SL_CLIENTID= 267 AND s.SLC_CODE= 13 AND s.SLT_CODE= 15 AND
s.REF_NO= s.REF_NO AND s.TR_DATE >= (SELECT s.TR_DATE FROM sldtl AS s ORDER BY s.TR_DATE DESC LIMIT 1)-INTERVAL 6 MONTH
GROUP BY
s.TR_DATE DESC, s.TR_CODE, s.TR_CTLNO
需要的结果
+-----------+--------------+---------------+
| DEBIT | CREDIT | BALANCE |
+-----------+--------------+---------------+
| 0.00 | 700.00 | -700.00 |
| 0.00 | 700.00 | -1400.00 |
| 400.00 | 0.00 | -1000.00 |
| 2000.00 | 500.00 | 500.00 |
+-----------+--------------+---------------+
最佳答案
让我们考虑一下问题的简化版本:
只包含debit
和credit
列的表。您需要计算balance
列:
平衡:
debit credit
0 700
0 700
400 0
2000 500
SELECT
debit,
credit,
@balance := @balance + debit - credit AS balance
FROM balancetable, (SELECT @balance := 0) var;
SQL FIDDLE DEMO
所以在你的情况下会是:
SELECT
t.DEBIT,
t.CREDIT,
@balance := @balance + t.DEBIT - t.CREDIT AS BALANCE
FROM
(
SELECT SUM(IF(s.AMT>0 AND s.SLE_CODE=11,s.AMT,0)) AS DEBIT,
SUM(IF(s.AMT<0 AND s.SLE_CODE=11,s.AMT,0)) * -1 AS CREDIT
FROM
sldtl AS s
LEFT JOIN
transtype
ON
transtype.TransTypeID = s.TR_CODE
WHERE
s.SL_BRCODE= 1 AND s.SL_CLIENTID= 267 AND s.SLC_CODE= 13 AND s.SLT_CODE= 15 AND
s.REF_NO= s.REF_NO AND s.TR_DATE >= (SELECT s.TR_DATE FROM sldtl AS s ORDER BY s.TR_DATE DESC LIMIT 1)-INTERVAL 6 MONTH
GROUP BY
s.TR_DATE DESC, s.TR_CODE, s.TR_CTLNO
) AS t , (SELECT @balance := 0) var;