随机抽取样本的问题,哪位能帮我??

写一个SQL语句,从10种颜色不同编号的100个球中随机抽取20个出来,保证这20个球的颜色尽可能平均分布在这10种颜色中,大伙说能实现吗?
---------------------------------------------------------------

20/10=2 then:

select top 2 * from table where color='color1' order by newid()
union all
select top 2 * from table where color='color2' order by newid()
union all
..........

select top 2 * from table where color='color10' order by newid()
---------------------------------------------------------------

select top 20 * from 表 order by newid()
---------------------------------------------------------------

1: select top 20 * from 表 order by newid() -- 对全部的球随机取

2:每种球随机取2个,不是尽量平均,而是100%平均。
select * from (select top 2 * from table1 where color='color1' order by newid()) a
union all
select * from (select top 2 * from table1 where color='color2' order by newid())a
union all
..........

select * from (select top 2 * from table where color='color10' order by newid())a

3:不要搞得太平均了。
select * from (select top 4 * from table1 where color IN ('color1','color2') order by newid()) a
union all
select * from (select top 4 * from table1 where color in ('color3','color4') order by newid())a
union all
..........

select * from (select top 4 * from table where color in ('color9','color10') order by newid())a

---------------------------------------------------------------

--更随机+平均的办法,用生成SQL的方法:

declare @sql varchar(8000),@i int
select @sql='',@i=0
while @i<10
select @sql=@sql+'
union all select top '+cast(cast(rand()*3 as int)+1 as varchar)
+' * from 表 where color =''color'+cast(@i as varchar)+''' order by newid()'
,@i=@i+1
set @sql=substring(@sql,16,8000)
exec('select top 20 * from('+ @sql+') a')

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus