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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | 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
 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
52326 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  
 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.03 seconds. Powered By: Snitz Forums 2000