sql中怎么判断某个字段的值是否连续?

usun82 2013-10-15 05:33:51
比如:A表的字段AID的值为:1、2、4、5、7、8、10
怎么用sql查询出2、5、8的结果呢?
要查的结果就是查询这组数据从哪里开始不连续的。
哪位大哥帮忙解决下,谢谢!
...全文
3516 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
潇洒王子 2013-10-21
  • 打赏
  • 举报
回复
貌似关联子查询就能实现。例如楼上的语句。
zhaowei303 2013-10-18
  • 打赏
  • 举报
回复
引用 9 楼 tcmakebest 的回复:
表与自己关联 select id from a t1 where not exists( select * from a t2 where t2.id=t1.id+1 ) 再去掉最大值
可以。
LongRui888 2013-10-15
  • 打赏
  • 举报
回复
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
*/
tcmakebest 2013-10-15
  • 打赏
  • 举报
回复
表与自己关联 select id from a t1 where not exists( select * from a t2 where t2.id=t1.id+1 ) 再去掉最大值
usun82 2013-10-15
  • 打赏
  • 举报
回复
sqlce,很多sqlserver的函数都不能用。
水族杰纶 2013-10-15
  • 打赏
  • 举报
回复
引用 6 楼 usun82 的回复:
能不能不用临时表,我的数据库不支持这种复杂的SQL,可以用表连接,不好意思。
啥数据库临时表 row_number都不支持? 数据量少的情况下 用master..spt_values吧 如果权限不足也会有问题
usun82 2013-10-15
  • 打赏
  • 举报
回复
能不能不用临时表,我的数据库不支持这种复杂的SQL,可以用表连接,不好意思。
唐诗三百首 2013-10-15
  • 打赏
  • 举报
回复
引用 4 楼 usun82 的回复:
能不能不用row_number()over搞定呢?刚才的方法把10也查出来了。
不用row_number()的方法.

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)
*/
usun82 2013-10-15
  • 打赏
  • 举报
回复
能不能不用row_number()over搞定呢?刚才的方法把10也查出来了。
唐诗三百首 2013-10-15
  • 打赏
  • 举报
回复

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)
*/
水族杰纶 2013-10-15
  • 打赏
  • 举报
回复
select max(t.aid)aid from( select aid,cnt=aid-row_number()over(order by getdate()) from tb )t group by cnt
水族杰纶 2013-10-15
  • 打赏
  • 举报
回复
通过辅助表实现吧 或者可以参考这帖 面试之BI-SQL--table转换

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧