简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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