如何计算运行平衡

时间:2009-11-26 10:29:11

标签: sql

SELECT              
    CONVERT (VARCHAR,GLTR_PSTNG_DATETIME,101) AS   GLTR_PSTNG_DATE,
    GLTR_DOC_CODE, GLTR_OUR_DOC_NO,     
    CONVERT (VARCHAR,GLTR_DOC_DATETIME,101) AS   GLTR_DOC_DATETIME,
    GLTR_TRAN_AMT, GLTR_FC_CODE,            
    GLTR_FC_AMT          
FROM            
    GLAS_GL_TRANSACTIONS            
WHERE            
    GLTR_COMP_CODE = '1' 
    AND GLTR_ACCT_CODE = SUBSTRING('1110011',4,4)            
    AND GLTR_PSTNG_DATETIME  BETWEEN '05/13/2008' AND '11/26/2009'          
    AND ISNULL('bv',GLTR_DOC_CODE) = GLTR_DOC_CODE
GROUP BY
    GLTR_PSTNG_DATEtime

这个查询是从数据库中提取到网格的,我的场景是当transamt检索它时​​应该计算运行余额并且应该显示它。

它应该显示如下(运行余额不是数据库字段项)

gltr_tran_amt  running balance
-480.000        -480.000
 480.000         0
-2540.500       -2540.500
 2540.500        0
-3800.000       -3800.00
 3800.000        0
 500             500
 1000            1500

它应该检索并显示如下

1 个答案:

答案 0 :(得分:4)

好的,正如评论所说,你应该更好地说明你的问题。此外,提供架构可以提供更多帮助。

我想我知道你想做什么,这应该可以帮助你找到正确的方向

DECLARE @Table TABLE(
        ID INT IDENTITY(1,1),
        DateVal DATETIME,
        Amount FLOAT
)

INSERT INTO @Table (DateVal,Amount) SELECT '01 Jan 2009', -480
INSERT INTO @Table (DateVal,Amount) SELECT '01 Jan 2009', 480
INSERT INTO @Table (DateVal,Amount) SELECT '02 Jan 2009', -2540.500
INSERT INTO @Table (DateVal,Amount) SELECT '02 Jan 2009', 2540.500
INSERT INTO @Table (DateVal,Amount) SELECT '02 Jan 2009', -3800.000
INSERT INTO @Table (DateVal,Amount) SELECT '03 Jan 2009', 3800.000
INSERT INTO @Table (DateVal,Amount) SELECT '04 Jan 2009', 500
INSERT INTO @Table (DateVal,Amount) SELECT '05 Jan 2009', 1000

SELECT  * ,
        (SELECT SUM(Amount) FROM @Table WHERE ID <= t.ID) RunningTotal
FROM    @Table t