当前位置:首页 >> 饮食养生

求想在一个表中查询某个字段连续条物业

2021-09-06 09:58 来源:莱西养生网

求sql想在一个表中查询某个字段连续N条记录是连续+1的前一条记录

表记录 参数num=3(3 条相连(no连续+1)的记录)

id loclevel no

1 1 1

2 1 2

3 1 4

4 1 5

5 1 6

6 2 1

7 2 2

8 2 3

9 2 4

我想得到的结果是

id loclevel no

3 1 4

6 2 1

7 2 2

也就是说 loclevel是1的情况下 id3到id5 NO字段是3次连续+1的(4,5,6) 所以把id3提出来

loclevel是2的情况下 id6到id8 NO字段是3次连续+1的(1,2,3) id7到id9 NO字段是3次连续+1的(2,3,4)

所以把id6,id7提出来

SQL code-- 测试数据: @s

declare @s table (id int,loclevel int,no int)

insert into @s

select 1,1,1 union all

select 2,1,2 union all

select 3,1,4 union all

select 4,1,5 union all

select 5,1,6 union all

select 6,2,1 union all

select 7,2,2 union all

select 8,2,3 union all

select 9,2,4

select * from @s a

where exists(select 1 from @s where loclevel=clevel and no=+1)

and exists(select 1 from @s where loclevel=clevel and no=+2)

--结果:

id loclevel no

----------- ----------- -----------

3 1 4

6 2 1

7 2 2

SQL codedeclare @t table(id int,loclevel int,no int)

insert into @t select 1,1,1

insert into @t select 2,1,2

insert into @t select 3,1,4

insert into @t select 4,1,5

insert into @t select 5,1,6

insert into @t select 6,2,1

insert into @t select 7,2,2

insert into @t select 8,2,3

insert into @t select 9,2,4

select

a.*

from

@t a,@t b,@t c

where

=-1 and =-1 and clevel=clevel

and

=-2 and =-2 and clevel=clevel

SQL codedeclare @t table(id int,loclevel int,no int)

insert into @t select 1,1,1

insert into @t select 2,1,2

insert into @t select 3,1,4

insert into @t select 4,1,5

insert into @t select 5,1,6

insert into @t select 6,2,1

insert into @t select 7,2,2

insert into @t select 8,2,3

insert into @t select 9,2,4

declare @i int

set @i=3 --当N值变化时,只需替换此处的@i值

select

a.*

from

@t a,

(select t.* from @t t where not exists(select 1 from @t where id=+1 and loclevel=clevel and no=+1)) b

where

= and clevel=clevel

group by

,clevel,

having

min()=@i-1

/*

id loclevel no

----------- ----------- -----------

3 1 4

6 2 1

7 2 2

同比下降16% */

拉萨妇科医院哪好
黄芪生脉饮需要注意哪些事
焦作白癜风医院
相关阅读
大白熊犬四肢无力是不是生病的前兆位置

大白熊犬四肢无力是不是生病了?快乐伴随:如果没有别的症状可以排除犬瘟,大白熊犬价格犬瘟会带有精神不好,食欲不振,流浓鼻涕,浓眼屎等症状。一般这种情况有几种可能:你开出的食谱中维生素的摄入过...

大白熊犬呕吐拉稀该吃什么食物位置

6个月大白熊犬,前天晚上受凉,昨天开始呕吐拉稀,便血。看医生之后吃药好转,一夜没有再吐也没拉,精神变好,食欲恢复.今天中午大便还是有点稀,带血.医生开的药也在吃,大白熊犬怎么喂养?风雪恋缘:大...

大白熊犬合理的梳理方法及其要领位置

大白熊犬属于大型的犬种,还拥有着一身雪白的毛发,想要它的毛发时时刻刻都保持着干净而且还顺滑光亮,家长们就必须勤给它梳理毛发,才可以基本保证让它拥有一个顺滑的毛发。给大白熊犬梳理毛发的好处数...

大白熊犬可以喝酸奶帮助肠胃消化吗位置

大白熊犬可以喝酸奶吗?平时可以吃点什么帮助肠胃健康。狼的诱惑:狗是可以喝酸牛奶的最好能挑选乳酸菌的 会对大白熊犬价格的肠胃和消化系统有好处因为酸奶的吸收率比牛奶高.和牛奶相比,酸奶中的钙没...

大白熊犬发情特征和交配需要注意的事项位置

大白熊犬发情特征,当家里养的大白熊犬开始学会抱着主人的腿或者遛狗的时候发现自己狗狗会抱着别的狗狗的时候,有些饲主就误以为家里的狗狗发情了,其实并不然,这只是宣誓的一种举动,那么大白熊犬真正...

大白熊犬为什么总吐拉稀位置

大白熊犬为什么会呕吐,拉稀。鼻子会流血?笑傲股林:如果你家大白熊犬有吃塑料袋,毛线,钓鱼线,袜子什么的,就要做B超活x光检查一下肠道;以上两点是不拉稀得情况下的结论。去检查一下吧。如果我是对...

友情链接