Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Updating SQl rows on the basis of previous row val

Author  Topic 

mehra.abhinav88
Starting Member

1 Post

Posted - 2013-04-03 : 02:20:24
Hi,

I need urgent help... I want to update row value which have some portion from previous row value. ( Basically I need to find carry over effect).

I am using While loop or cursor to do the same but it is taking alot of time as the update statement runs number of rows times.

Please suggest me a good efficient way to find out carry over effect. Below is the example of dataset with 0.2 carry over effect.

WeekNumber Var1 carry_over_effect_0.2
1 10 10
2 30 30+0.2*10
3 80 80+(30+0.2*10)*0.2

and so on

Thanks
Abhinav Mehra
mehra.abhinav88@gmail.com

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-04-03 : 02:26:15
try a recursive CTE approach

;With YourCTEName
AS
(
SELECT WeekNumber,Var1,Var1 AS carry_over_effect_0.2
FROM Table
WHERE WeekNumber=1

UNION ALL

SELECT t.WeekNumber,t.Var1,t.Var1 + 0.2 * c.carry_over_effect_0.2
FROM Table t
JOIN YourCTEName c
ON c.WeekNumber = t.WeekNumber -1
)

SELECT *
FROM YourCTENAme

OPTION (MAXRECURSION 0)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -