首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

随机抽样有关问题-求解

2013-02-03 
随机抽样问题-求解declare @a int,@b int,@c int,@d int,@e int,@f int,@h int,@g intselect @a0,@b0,@c

随机抽样问题-求解


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.

热点排行