我可以使用 SQL 的游标从上一行检索值吗?

发布于 2024-09-12 01:05:35 字数 92 浏览 2 评论 0原文

我正在开发一个查询,我需要当前行的某个字段是“当前行的字段”+“上一行的同一字段”的结果。 (SQL Server 2008)

如何使用游标来做到这一点?

I'm developing a query, where I need that a certain field of my current line be the result of "the field of my current line" + "the same field of the previous line". (SQL Server 2008)

How can I do it by using cursors?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飘逸的'云 2024-09-19 01:05:36

将上一行值分配给变量:

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;

Assign the previous line value to a variable:

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;
短暂陪伴 2024-09-19 01:05:36

这是使用 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
;

Would this be an appropriate solution using the 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
;
执笏见 2024-09-19 01:05:36

我确实相信 FETCH PRIOR 在 SQLServer 2008 中可用....参见
此 MS 页面

I do believe FETCH PRIOR is available in SQLServer 2008....See
this MS page

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文