2010-07-27 51 views
2

我正在開發一個查詢,我需要將當前行的某個字段作爲「當前行的字段」+「上一行的同一字段」的結果。 (SQL Server 2008)我可以使用CURSORs從前一行檢索一個值嗎?

我該如何使用遊標來做到這一點?

+0

給我們一些示例數據和表模式,它可以用熱膨脹係數,最有可能排名函數來完成... – gbn 2010-07-27 17:43:48

回答

5

前一行值分配給一個變量:

declare @previosvalue varchar(100) = null; 
declare @currentvalue varchar(100); 

declare crs cursor for select value from table; 
open crs; 

fetch next from crs into @currentvalue; 
while @@fetch_status = 0 
begin 
    -- process here. On first row, @previousvalue is NULL 
    -- as it should be, since there is no 'previous' of first 

    select ... from sometable 
    where somecondition = @currentvalue 
    and othercondition = @previousvalue; 

    set @previousvalue = @currentvalue; 
    fetch next from crs into @currentvalue; 
end 

close crs; 
deallocate crs; 
+0

會的CTE不是一點點更優雅......? – gbn 2010-07-27 17:47:33

+2

@gbn:我想要'LEAD'和'LAG'支持,我自己 – 2010-07-27 17:50:40

+0

@OMG小馬:是的,忘了那些...... – gbn 2010-07-27 17:52:35

1

這將是使用CTE適當的溶液?

WITH MyCTE AS 
    (SELECT ROW_NUMBER() OVER (ORDER BY col1) AS Sequence, Col1, Col2 
    FROM Table1) 

SELECT c1.Sequence, c1.Col1 AS Prev_Co1, 
    c2.Col1 AS Cur_Col1, c1.Col2 AS Prev_Col2, c2.Col2 AS Cur_Col2, 
    COALESCE(c1.Col2, 0) + COALESCE(c2.Col2, 0) AS Sum_Col2 
FROM MyCTE AS c1 
LEFT OUTER JOIN MyCTE AS c2 ON c1.Sequence = c2.Sequence + 1 
; 
+0

對不起,但我對CTE一無所知......但很快我會開始學習這是如何工作的。謝謝! – Kira 2010-07-27 18:55:42

相關問題