2010-07-27 49 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

相关问题