SQL无法将上一行的值添加到下一行

时间:2016-07-21 19:55:43

标签: sql sql-server-2008

我正在尝试将前一行的值添加到当前行的累积值

Select 
    Ddate as Date, etype, Reference, linkacc as ContraAcc,
    Description,
    sum(case when amount > 0 then amount else 0 end) as Debits,
    sum(case when amount < 0 then amount else 0 end) as Credits,
    sum(amount) as Cumulative
from
    dbo.vw_LT
where
    accnumber ='8400000' 
    and [DDate] between '2016-04-01 00:00:00' and '2016-04-30 00:00:00'
    and [DataSource] = 'PAS11CEDCRE17'
group by 
    Ddate, etype, Reference, linkacc, Description, Amount

输出(我得到的):

Date        Reference   ContraAcc   Description Debits  Credits Cumulative 
--------------------------------------------------------------------------
2016-04-01     CC007    8000000     D/CC007      0      -39.19    -39.19
2016-04-01     CC007    8000000     D/CC007     1117.09     0     1117.09
2016-04-01     CC009    8000000     CC009       2600        0       2600
累积列中的

应该如下(我需要的):

Date        Reference   ContraAcc   Description Debits  Credits Cumulative 
--------------------------------------------------------------------------
2016-04-01     CC007    8000000     D/CC007      0      -39.19    -39.19
2016-04-01     CC007    8000000     D/CC007     1117.09     0     1077.9
2016-04-01     CC009    8000000     CC009       2600        0     3677.9

1 个答案:

答案 0 :(得分:1)

在我们深入研究解决方案之前,让我告诉您,如果您使用的SQL Server版本超过2012年,则有LAGLEAD,可以帮助您解决此问题。

我没有给你一个确切的查询来解决你的问题(因为我们不知道那个表的主键是什么),但是你可以通过看下面的例子得到这个想法

DECLARE @t TABLE
(
    accountNumber   VARCHAR(50)
    ,dt             DATETIME
    ,TransactedAmt  BIGINT
)

INSERT INTO @t VALUES ('0001','7/20/2016',1000)
INSERT INTO @t VALUES ('0001','7/21/2016',-1000)
INSERT INTO @t VALUES ('0001','7/22/2016',2000)

INSERT INTO @t VALUES ('0002','7/20/2016',500)
INSERT INTO @t VALUES ('0002','7/21/2016',-500)
INSERT INTO @t VALUES ('0002','7/22/2016',2000)

;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(Partition by accountNumber order by dt) as RN, * 
    FROM @t
),CTE1 AS
(
    SELECT *,TransactedAmt As TotalBalance
    FROM CTE WHERE rn = 1
    UNION
    SELECT T1.*,T1.TransactedAmt + T0.TransactedAmt as TotalBalance
    FROM CTE T1
    JOIN CTE    T0
    ON  T1.accountNumber = T0.accountNumber
    AND T1.RN = T0.RN+1
    AND T1.RN > 1
)
select * from CTE1 order by AccountNumber