如何使用下面的查询获取每行的BALANCE

时间:2016-06-22 03:49:08

标签: mysql

我想获得每笔借方和贷方的余额,然后计算每行的余额..

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

2 个答案:

答案 0 :(得分:3)

让我们考虑问题的简化版本:

仅包含debitcredit列的表格。并且您想要计算balance列:

<强> balanceTable:

 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;

答案 1 :(得分:1)

如果在选择结尾添加@balance:

SELECT @debit : = SUM(IF(s.AMT>0 AND s.SLE_CODE=11,s.AMT,0)) AS DEBIT,
    @credit := SUM(IF(s.AMT<0 AND s.SLE_CODE=11,s.AMT,0)) * -1 AS CREDIT,
    @balance := @balance - @credit + @debit As BALANCE
FROM sldtl AS s
LEFT JOIN transtype ON transtype.TransTypeID = s.TR_CODE
JOIN (SELECT @balance := 0) AS tmp
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

PS:我没有阅读你剩下的SQL