加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLServer 某列值连续4行相同则输出其1行(测试)

发布时间:2020-12-12 12:49:42 所属栏目:MsSql教程 来源:网络整理
导读:--drop table testcreate table test(name varchar(20),value int)insert into test(name,value)values('aa',1),('pp',('hh',-1),('ff',('ee',('aa',('jj',('oo',('uu',('bb',('ll',-1)select * from test 以上红框中是要输出的结果:输出为1的,连续4行为1


--	drop table test
create table test(name varchar(20),value int)

insert into test(name,value)
values('aa',1),('pp',('hh',-1),('ff',('ee',('aa',('jj',('oo',('uu',('bb',('ll',-1)

select * from test



以上红框中是要输出的结果:输出为1的,连续4行为1则输出第四行值

7 aa 1
13 ff 1
17 ll 1


使用游标的方法:

declare @id int
declare @name varchar(20)
declare @value int
declare @id2 int
declare @value2 int
declare @mk int
set @mk = 1
declare cur cursor local fast_forward 
	for select row_number()over(order by (select 0)) as id,name,value from test
open cur
fetch next from cur into @id,@name,@value
while @@fetch_status = 0
begin
	set @id2 = @id
	set @value2 = @value
	fetch next from cur into @id,@value
	if(@id2+1=@id and @value2 = @value and @value=1)
	begin
		set @mk = @mk +1
		if (@mk = 4)
		begin
			--结果输出或者插入到某个表中
			select @id as id,@name as name,@value as value
			set @mk = 0
		end
	end
	else set @mk = 1
end
close cur
deallocate cur

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读