日期:2014-05-17  浏览次数:20571 次

随机抽样问题-求解
本帖最后由 pplive1989 于 2013-01-27 23:26:55 编辑
--随机取值,要求:3男.3女,其中3个0001班的,1个0002班的,2个0003班的,并且2个是1989生的,2个是1990生的,2个1991生的
--数据表class(cid,name,sid,ssex,birthday)
有谁帮忙看看哪错了,class表一共就14行数据抽6行还能抽半天没反应- -跑了17分钟都木有输出结果,我自己手拼都拼好几组了

declare @a int,@b int,@c int,@d int,@e int,@f int,@h int,@g int
select @a=0,@b=0,@c=0,@d=0,@e=0,@f=0,@h=0,@g=0;
while @a!=3 or @b!=1 or @c!=2 or @d!=3 or @e!=3 or @f!=2 or @h!=2 or @g!=2
   begin
      if OBJECT_ID('tb')is not null
      drop table tb;
      with cte_a(id,cid,sid,name,ssex,birthday)
      as
      (select top(6)NEWID()as id,cid,sid,name,ssex,birthday from class order by NEWID())
      select cid,sid,name,ssex,birthday into tb from cte_a
      select @a=(select COUNT(cid) from tb where cid='0001')
      ,@b=(select COUNT(cid) from tb where cid='0002')
      ,@c=(select COUNT(cid) from tb where cid='0003')
      ,@d=(select COUNT(ssex) from tb where ssex=1)
      ,@e=(select COUNT(ssex) from tb where ssex=0)
      ,@f=(select COUNT(birthday) from tb where year(birthday)=1989)
      ,@h=(select COUNT(birthday) from tb where year(birthday)=1990)
      ,@g=(select COUNT(birthday) from tb where year(birthday)=1991)
   end
select * from tb

------解决方案--------------------
简单说就是你的数据量太少,随机取得数据很难符合你的条件,因而一直循环
你可以从1班直接随机3人,2班随机1人,3班随机2人
或者再加些条件,出生在1989-1991的,
或者多加一些有效数据进去,不然假设你只有4条1班的,随机一整晚,
数据库一直都能随机到1班4个人或1或2,就不随机到3,那你得等到过年了~
------解决方案--------------------
这问题有意思,将14条数据贴出来看看,毫无疑问数据越少,随机性选择越差。
------解决方案--------------------
三种思路抽取。
1、随机取一条,且该条记录不在最终表。
满足所有条件且条件没有益出 则把该条数据存到最终表。不满足则重新取。一直到取到满足所有数据为止。

2、先按照最大的条件取。如先从男的里面抽取3条,女的里面抽取3条。然后再判断是否满足其余条件。这样可以减少随机的量。

3、列出随机14条数据的所有组合,然后取出所有满足条件的。之后再select top 1 order by newid.

lz没给出基础的数据量。因此个人认为第一种取法最适合lz.