SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Updating SQl rows on the basis of previous row val
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mehra.abhinav88
Starting Member

India
1 Posts

Posted - 04/03/2013 :  02:20:24  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 04/03/2013 :  02:26:15  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000