日期:2014-05-19  浏览次数:20430 次

求助:随机取一组连续的记录
如表:
temID
1
2
3
4
5
6
7
8

如果取3条记录,结果可以是:
1
2
3

4
5
6

7
8
1

8
1
2
等等




------解决方案--------------------
select top 3 * from table order by newid()
------解决方案--------------------

--创建测试环境
create table 表名 (tempid int)

--追加测试数据
insert into 表名
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8


create table #t (id int identity(1,1),tempid int)

declare @tempid int

set @tempid=(select top 1 tempid from 表名 order by newid())

--追加第一个随机数
insert into #t(tempid) select @tempid

--追加大于这个数据的tempid,取> @tmepid 的2条记录,可能不存在
insert into #t
select top 2 tempid
from 表名
where tempid> @tempid
order by tempid


--如果不满3条,继续从开始的记录追加,最多需要追加2条
insert into #t(tempid)
select top 2 tempid
from 表名
order by tempid

--按照追加的顺序,取前3条即可
select top 3 tempid from #t order by id

--删除测试表
drop table #t,表名