22,209
社区成员
发帖
与我相关
我的任务
分享
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[used] nvarchar(25))
Insert #T
select 1,N'true' union all
select 2,N'false' union all
select 3,N'false' union all
select 4,N'false' union all
select 5,N'false' union all
select 6,N'true' union all
select 7,N'true' union all
select 8,N'false' union all
select 9,N'false' union all
select 10,N'false' union all
select 11,N'false' union all
select 12,N'false' union all
select 13,N'true'
Go
;with t as
(select pid=id-row_number()over(order by id),rid=row_number()over(order by id),* from #t where used='false')
select top 3 * from #t
where id>=(select top 1 id from t t1 where exists(select 1 from t t2 where t1.pid=t2.pid and t2.id=t1.id+2) order by newid())
order by id
结果 5种可能
适合id顺序 但是不一定连续的情况--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[used] nvarchar(25))
Insert #T
select 1,N'true' union all
select 2,N'false' union all
select 3,N'false' union all
select 4,N'false' union all
select 5,N'false' union all
select 6,N'true' union all
select 7,N'ture' union all
select 8,N'false' union all
select 9,N'false' union all
select 10,N'false' union all
select 11,N'false' union all
select 12,N'false' union all
select 13,N'true'
Go
--测试数据结束
;WITH ctea AS (
SELECT * ,
id - ROW_NUMBER() OVER ( ORDER BY id ) AS num
FROM #T
WHERE used = 'false'
),cteb AS (
SELECT num,COUNT(1) AS rcount FROM ctea GROUP BY num HAVING COUNT(1)>2
)
SELECT TOP 3
*
FROM ctea
WHERE num = ( SELECT TOP 1
num
FROM cteb
ORDER BY NEWID()
)
ORDER BY id