如何在SQL中计算运行余额

时间:2017-03-20 07:26:15

标签: sql derby running-total

我正在使用嵌入式德比数据库,我想通过计算借方和贷方金额来添加运行余额列,所以请告诉我解决方案代码和图片也可以在下面找到

(正如您在图像平衡中看到的总计不准确)

SELECT 
V_DATE,FLAG,V_NUM,V_NARATION,
sum(VDTL.DR_AMOUNT) AS DEBIT,
sum(VDTL.CR_AMOUNT) AS CRIDIT,
sum(dr_amount)-sum(cr_amount) as total
FROM VOUCHARDETAIL AS VDTL
INNER JOIN VOUCHARMASTER AS VMST
ON VDTL.DTL_NUM =VMST.MST_NUM
WHERE (V_DATE BETWEEN '12-03-2017' AND '14-03-2017') AND (FLAG='IV' OR FLAG='BR'
OR FLAG='CP' OR FLAG='CR' OR FLAG='JV' OR FLAG='BP') AND (AC_CODE=60030002) 
GROUP BY
V_DATE,FLAG,V_NUM,V_NARATION
ORDER BY
V_DATE

image

1 个答案:

答案 0 :(得分:1)

Begin Tran

--------------------------------------------------------------------
--Sample Data for Running Total 
--------------------------------------------------------------------
CREATE TABLE RunTotalTestData (
   id    int not null identity(1,1) primary key,
   value int not null
);

INSERT INTO RunTotalTestData (value) VALUES (1);
INSERT INTO RunTotalTestData (value) VALUES (2);
INSERT INTO RunTotalTestData (value) VALUES (4);
INSERT INTO RunTotalTestData (value) VALUES (7);
INSERT INTO RunTotalTestData (value) VALUES (9);
INSERT INTO RunTotalTestData (value) VALUES (12);
INSERT INTO RunTotalTestData (value) VALUES (13);
INSERT INTO RunTotalTestData (value) VALUES (16);
INSERT INTO RunTotalTestData (value) VALUES (22);
INSERT INTO RunTotalTestData (value) VALUES (42);
INSERT INTO RunTotalTestData (value) VALUES (57);
INSERT INTO RunTotalTestData (value) VALUES (58);
INSERT INTO RunTotalTestData (value) VALUES (59);
INSERT INTO RunTotalTestData (value) VALUES (60);


SELECT a.id, a.value, (SELECT SUM(b.value)
                       FROM RunTotalTestData b
                       WHERE b.id <= a.id) Runningtotal
FROM   RunTotalTestData a
ORDER BY a.id;

RollBack Tran