简体   繁体   English

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

[英]SQL failing to add value from previous row into the next

I am trying to add the value of the previous row to the current row into the column cumulative 我正在尝试将当前行的前一行的值添加到累积列中

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

Output(what i am getting): 输出(我得到的):

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

in the cumulative column should like below(what i need): 在累积列中应如下所示(我需要):

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

Before we delve into the solution, let me tell you that if you are using SQL Server version more than 2012, there are LAG and LEAD , which can help you to solve this. 在深入研究该解决方案之前,让我告诉您,如果您使用的SQL Server版本大于2012,则存在LAGLEAD ,它们可以帮助您解决此问题。

I am not giving you an exact query to solve your problem (as we dont know what your primary key for that table is), but you can get the idea by seeing the below example 我没有为您提供确切的查询来解决您的问题(因为我们不知道该表的主键是什么),但是您可以通过查看以下示例来了解一下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM