2010-07-07 117 views
0

我正在嘗試在'Value'列中根據前一行記錄在'Increment'列中執行一些操作SQL Server逐行操作

例如,

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

我想基於公式

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 

將光標適用這裏更新列「衰變」?語法怎麼樣? 謝謝

+2

6個問題,0接受? 「再見。 – egrunin 2010-07-07 04:57:40

+0

很酷。謝謝!不知道它是這樣工作的 – marilyn 2010-07-07 08:39:45

回答

3

下面是一個使用遞歸CTE(也注意到,在您的示例算術是不正確的)a running example

-- 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​ 
0
UPDATE 
    tbl_test 
SET 
    col_name = 'xyq' 
FROM 
    (
    SELECT 
     *, 
     ROW_NUMBER() OVER (ORDER BY name) AS rno 
    FROM 
    tbl_test 
    )tbl_test 
WHERE 
    rno = 3 

--rno is the rownumber that u want to update