sql中怎么判断某个字段的值是否连续?
比如:A表的字段AID的值为:1、2、4、5、7、8、10
怎么用sql查询出2、5、8的结果呢?
要查的结果就是查询这组数据从哪里开始不连续的。
哪位大哥帮忙解决下,谢谢!
[解决办法]
select
max(t.aid)aid
from(
select aid,cnt=aid-row_number()over(order by getdate()) from tb
)t group by cnt
[解决办法]
create table A表(AID int)
insert into A表(AID)
select 1 union all
select 2 union all
select 4 union all
select 5 union all
select 7 union all
select 8 union all
select 10
with t as
(select AID,row_number() over(order by AID) 'rn'
from A表
)
select a.AID
from t a
left join t b on a.rn=b.rn-1
where b.rn is not null and a.AID<>b.AID-1
/*
AID
-----------
2
5
8
(3 row(s) affected)
*/
create table A表(AID int)
insert into A表(AID)
select 1 union all
select 2 union all
select 4 union all
select 5 union all
select 7 union all
select 8 union all
select 10
select identity(int,1,1) 'rn',AID
into #t
from A表
select a.AID
from #t a
left join #t b on a.rn=b.rn-1
where b.rn is not null and a.AID<>b.AID-1
/*
AID
-----------
2
5
8
(3 row(s) affected)
*/
create table A(AID int)
insert into A(AID)
select 1 union all
select 2 union all
select 4 union all
select 5 union all
select 7 union all
select 8 union all
select 10
select aid
from
(
select a.aid,
(select min(aid) from a aa where aa.aid > a.aid) min_aid
from A
)a
where aid +1 < min_aid
/*
aid
2
5
8
*/