這樣的事情?
/*
DROP TABLE T;
CREATE TABLE T(NAME VARCHAR(3),ID INT, TRTYPE VARCHAR(1), AMOUNT INT);
INSERT INTO T VALUES
('abc',1,'D','500'),('abc',1,'C','50'),('abc',1,'C','10'),('abc',1,'C','40'),
('abc',1,'D','500'),('abc',1,'C','100');
*/
SELECT S.NAME,S.ID,S.DEBIT,S.CREDIT,s.runtot runningtotal,
CASE WHEN S.DEBIT <> '' THEN S.RUNTOT ELSE '' END AS DebitRunningTotal,
CASE WHEN S.DEBIT = '' THEN S.RUNTOT ELSE '' END AS CreditRunningTotal
from
(
SELECT T.NAME,T.ID,
CASE WHEN T.TRTYPE = 'D' THEN T.AMOUNT ELSE '' END AS DEBIT,
CASE WHEN T.TRTYPE = 'C' THEN T.AMOUNT ELSE '' END AS CREDIT,
@RUNTOT:[email protected] + (
CASE WHEN TRTYPE = 'D' THEN AMOUNT
ELSE AMOUNT * -1
END)
AS RUNTOT
FROM (SELECT @RUNTOT:=0) RT, T T
) s
+------+------+-------+--------+--------------+-------------------+--------------------+
| NAME | ID | DEBIT | CREDIT | runningtotal | DebitRunningTotal | CreditRunningTotal |
+------+------+-------+--------+--------------+-------------------+--------------------+
| abc | 1 | 500 | | 500 | 500 | |
| abc | 1 | | 50 | 450 | | 450 |
| abc | 1 | | 10 | 440 | | 440 |
| abc | 1 | | 40 | 400 | | 400 |
| abc | 1 | 500 | | 900 | 900 | |
| abc | 1 | | 100 | 800 | | 800 |
+------+------+-------+--------+--------------+-------------------+--------------------+