根据记录类型计算总和

时间:2016-09-19 09:56:26

标签: php mysql

我坚持像图片这样的计算功能,我只能通过借记进行求和。

歌手是他的系统

Saldo =如果位置第1列第2列信用借记借记那么结果 - 信用,信用IF第1列第2列信用,那么结果是信用 - 信用,信用IF第1列第2列借方,贷方+借方那么结果,等等图片

results

这是我的代码

select 
    no, 
    tanggal, 
    O.debet,
    (select sum(debet) from tbl_jurnal_umum where no <= O.no) 'Saldo'
from tbl_jurnal_umum O 
where nama_perkiraan = 'kas'

1 个答案:

答案 0 :(得分:0)

这样的东西?

/*
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:=@RUNTOT + (
            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                |
+------+------+-------+--------+--------------+-------------------+--------------------+