表 a
Id    Count
1     2
2     2
3     1
4     1
5     2
6     2
7     1
8     2
9     1
10    2我想从上表中随机选取几条记录,这几条记录的sum(Count) = 5sql应如何写?
多谢!!

解决方案 »

  1.   

    drop table a
    CREATE TABLE a (Id int,    Count int)
    insert a
    select 1   ,  2
    union all select 2    , 2
    union all select 3  ,   1
    union all select 4  ,   1
    union all select 5  ,   2
    union all select 6  ,   2
    union all select 7  ,   1
    union all select 8   ,  2
    union all select 9  ,   1
    union all select 10  ,  2declare @tb table(num varchar(50),id int,Count int)
    insert @tb
    select newid(),* from aselect * from @tb c where 5>=(select sum(count) from @tb t where c.num>=t.num)
      

  2.   

    -------用newid()生成一个随机号,然后插入到一个表变量中,只查找就可以了
      

  3.   

    樓主做了測試沒有?結果是正確的?如果是要得到sum(Count) <= 5的,沒有問題。