日期:2014-05-19  浏览次数:20428 次

sql语句!
表AA
  id         user_id       class_id     shu
  1             100                   2             50
  2             200                   4               5
  3             100                   3             10
  4             300                   2             20
  5             400                   2             20
结果:
      注:(class_id=2   中包涵了3个user_id)
      要在class_id=2   中随机选择一条记录出来!就是选(3个user_id中的其中一个)
      但是:选择随机的机率性一定要在shu上
如:   shu=50就是说这条的记录重复了50次
  id         user_id       class_id     shu
  1             100                   2             50
  1             100                   2             50
  1             100                   2             50
  1             100                   2             50
  ……………………………………
    那么语句就好写了
  select   top   1   *   from   AA   where   class_id=2   order   by   newid()
但是我的shu是次数   不是一条条的记录!
随机的机率性一定要公平合理!按我上面的怎么写啊!
高手指点!


------解决方案--------------------
declare @t table(id int,[user_id] int,class_id int,shu int)
insert @t select 1, 100, 2, 50
union all select 2, 200, 4, 5
union all select 3, 100, 3, 10
union all select 4, 300, 2, 20
union all select 5, 400, 2, 20
union all select 6, 100, 5, 20

select class_id,rand(checksum(newid())) as randnum into #t from @t group by class_id
select id,[user_id],t.class_id,shu from
(select *,(select isnull(sum(shu),0) from @t where class_id=a.class_id) as total,
(select isnull(sum(shu),0) from @t where id <a.id and class_id=a.class_id) as pre from @t a) t
inner join #t on t.class_ID=#t.class_id where randnum*total> =pre and randnum*total <pre+shu
drop table #t

---结果不定
------解决方案--------------------
楼上厉害,学习