sql中怎么循环处理当前行数据和上一行数据相加减

本篇内容主要讲解“sql中怎么循环处理当前行数据和上一行数据相加减”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“sql中怎么循环处理当前行数据和上一行数据相加减”吧!

 以下事例,使用游标循环表#temptable中数据,然后让当前行和上一行中的argument1 相加 存放到当前行的 argument2 中,比较简单。

--drop table #temptablecreate table #temptable(  argument1 int,  argument2 int,  argument3 datetime)declare @rowcount int,@argument1 int,@argument2 nvarchar(50),@argument3 datetimeset @rowcount=1set @argument1=1set @argument2=0set @argument3=GETDATE()while(@rowcount<100)begin  insert into #temptable(argument1,argument2,argument3)        values(@argument1,@argument2,@argument3)    set @argument1=@argument1 + datepart(day,@argument3)  set @argument3=@argument3-1    set @rowcount = @rowcount + 1end--select * from #temptabledeclare @lastargument2 intset @lastargument2=0set @argument2=0declare _cursor cursor for(select argument1 from #temptable)open _cursor;fetch next from _cursor into @argument2 while @@fetch_status = 0begin        update #temptable  set argument2=@argument2+@lastargument2  where current of _cursor    set @lastargument2=@argument2    fetch next from _cursor into @argument2 endclose _cursordeallocate _cursor--select * from #temptable

到此,相信大家对“sql中怎么循环处理当前行数据和上一行数据相加减”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!