sql server - Calculating value using previous value of a row in T-SQL -


i got following table , want calculate value of column2 on each row using value of same column (column2) previous row in sql without using cursor or while loop.

id   date             column1    column2 1    01/01/2011       5          5 => same column1 2    02/01/2011       2          18 => (1 + (value of column2 previous row)) * (1 + (value of column1 current row)) i.e. (1+5)*(1+2) 3    03/01/2011       3          76 => (1+18)*(1+3) = 19*4 , on 

any thoughts?


assuming @ least sql server 2005 recursive cte:

;with ctecalculation (     select t.id, t.date, t.column1, t.column1 column2         yourtable t         t.id = 1     union     select t.id, t.date, t.column1, (1+t.column1)*(1+c.column2) column2         yourtable t             inner join ctecalculation c                 on t.id-1 = c.id ) select c.id, c.date, c.column1, c.column2     ctecalculation c 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -