select top n * from yourtable where col='条件' order by newid()
select top 10 * from TableName where columnName1 = 'Condition1' order by newid() union all select top 10 * from TableName where columnName2 = 'Condition2' order by newid() union all select top 10 * from TableName where columnName3 = 'Condition3' order by newid()
select top 10 * into #t1 from yourtable where col='条件1' order by newid() select top 10 * into #t2 from yourtable where col='条件2' order by newid() select top 10 * into #t3 from yourtable where col='条件3' order by newid()select * from #t1 union select * from #t2 union select * from #t3drop table #t1 drop table #t2 drop table #t3
可是没有完,我要找三次的合并,如何做?
即取100条中符合A条件的10条随机记录和符合B条件的10条随机记录和符合C条件的10条随机记录,一块显示,怎么办?
union all
select top 10 * from TableName where columnName2 = 'Condition2' order by newid()
union all
select top 10 * from TableName where columnName3 = 'Condition3' order by newid()
或者创建一张临时表(最好带主键,因为你的随机记录可能重复)然后将符合条件的数据插入到临时表中.
select top 10 * into #t2 from yourtable where col='条件2' order by newid()
select top 10 * into #t3 from yourtable where col='条件3' order by newid()select * from #t1
union
select * from #t2
union
select * from #t3drop table #t1
drop table #t2
drop table #t3