Search code examples
sqlsql-servercursorrow

SQL Server Row by Row operation


I am trying to do some operation in column 'Increment' based on previous row record in column 'Value'

e.g.

row_num| Period | Measure | Decay
1      | Jan 08 | 10      | 
2      | Feb 08 | 18      | 
3      | Mar 08 | 7       | 
4      | Apr 08 | 67      | 

i would like to update column 'Decay' based on a formula

row_num| Period | Measure| Decay
1      | Jan 08 | 10     | = 10             -> first value in 'Measures'
2      | Feb 08 | 18     | = 10*0.5+18 = 23 -> previous decay record *0.5 + current measure
3      | Mar 08 | 7      | = 23*0.5+7  = 18.5
4      | Apr 08 | 67     | = 18.5*0.5+67 = 76.25

would cursor be applicable here? how would the syntax be like? thank you


Solution

  • Here's a running example using a recursive CTE (also note that the arithmetic in your example is incorrect):

    -- SO3192010
    
    DECLARE @t AS TABLE (row_num int NOT NULL, Period varchar(6) NOT NULL, Measure float NOT NULL)
    INSERT INTO @t VALUES (1, 'Jan 08', 10)
        ,(2, 'Feb 08', 18)
        ,(3, 'Mar 08', 7)
        ,(4, 'Apr 08', 67)
    
    ;WITH r AS (
        SELECT t.*, Measure AS Decay
        FROM @t AS t
        WHERE t.row_num = 1
    
        UNION ALL
    
        SELECT t.*, r.Decay * 0.5 + t.Measure AS Decay
        FROM r
        INNER JOIN @t AS t
            ON t.row_num = r.row_num + 1
    )
    SELECT *
    FROM r
    ORDER BY row_num​