Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys,I am using Sql server 2012 . I have a table
i.e
Column1
32
-153
174
-5

I want result table like
C#
Column1 Column2
32        32
-153      -121 
174       53 
-5        48 

...
in Each Row next row value is added with prev value
i.e -153 + 32 =-121
-121+174=53

I heard about Lead and Lag in Sql server 2012 but not yet used.If you have any idea then let me know..
Posted
Updated 7-Feb-15 1:00am
v2

 
Share this answer
 
Try this:
WITH cte1 AS 
(
    select   column1,
             rownum = row_number() OVER (ORDER BY (SELECT 0))
    from     table1 
)
SELECT column1,
case rownum
  when 1 then column1 else
column1 + 
(
  select sum(column1) from cte1 c2 where c2.rownum < c1.rownum
)
end
FROM    cte1 c1
WHERE   rownum > 0
 
Share this answer
 
What you describe here is called running total. It is a quite common discussion topic and there are several approaches. Yes, SQL 2012 itroduced some feature that are supportung such queries. I suggest you read this extensive article about the possibilities you might have, and their performance considerations:
http://sqlperformance.com/2012/07/t-sql-queries/running-totals[^]
LEAD and LAG are not for that, as they can be used to access the NEXT and PREVIOUS rows in your set, but you can't use them to accumulate, as your cumulation is not part of the set (see this article: http://www.bidn.com/blogs/KathiKellenberger/sql-server/3300/don-t-get-left-behind-learn-to-use-lag[^]).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900