我知道怎么随机取3个数字并显示总和;但是怎么样才能加上总和为24的条件呢?
select top 3 * from fundrun..Test 
order by newid()
--having sum(a) = 24
compute sum(a)

解决方案 »

  1.   

    本来用另一种方法也可以实现:
    select a.a as a_a, b.a as b_a, c.a as c_a, (a.a + b.a + c.a) as sums
    from fundrun..Test a, fundrun..Test b, fundrun..Test c
    where a.a < b.a and a.a < c.a and b.a < c.a
    and (a.a + b.a + c.a) = 24
    但是还是想各位能否给出利用方法:select top 3 * from fundrun..Test 
    order by newid()
    实现的?
      

  2.   

    --舉個例子:declare @i int
    declare @t table (id int)
    set @i=-100
    while @i<=100
    begin
       insert into @t select @i 
       set @i=@i+1
    end--隨即3個數,和為24  
    select A.id, B.id, 24-A.id-B.id  from 
     (select top 1 id from @t order by newid()) A ,
     (select top 1 id from @t order by newid()) B
      

  3.   

    一般了,不能保證第3個數字在table中
      

  4.   

    ----------楼主的需求
    select top 1 * 
    from fundrun..Test a, fundrun..Test b, fundrun..Test c
    WHERE a.col+b.col+c.col=24
    order by newid()-----------产生三个随机数,它们的和为24
    SELECT TOP 1 a.colid,b.colid,c.colid
    FROM syscolumns a, syscolumns b, syscolumns c
    WHERE a.id=object_id('sysobjects')
    AND b.id=object_id('sysobjects')
    AND c.id=object_id('sysobjects')
    AND a.colid+b.colid+c.colid=24
    ORDER BY NEWID()
      

  5.   

    declare @i int
    declare @t table (id int)
    set @i=-100
    while @i<=100
    begin
       insert into @t select @i 
       set @i=@i+1
    end--隨即3個數,和為24  
    select A.id, B.id, 24-A.id-B.id  from 
     (select top 1 id from @t order by newid()) A ,
     (select top 1 id from @t order by newid()) B
    where A.id+B.id<=124 and A.id+B.id>=-76 
    這樣就可以保證 3個數字都在 tabl中
      

  6.   

    where A.id+B.id<=124 and A.id+B.id>=-76 --這一句改改好點
    where (A.id+B.id) between -76 and 124
      

  7.   

    --總結declare @i int
    declare @t table (id int)
    set @i=-100
    while @i<=100
    begin
       insert into @t select @i 
       set @i=@i+1
    end
    --SQL
    select A.id as col1, B.id as col2, (24-A.id-B.id) as col3  from 
    (select top 1 id from @t order by newid()) A,
    (select top 1 id from @t order by newid()) B
    --where (A.id+B.id) between -76 and 124 可以保證 3個數字都在 @t 中,但會出現空記錄
    --不加 where 時,不能保證第3個數字在 @t 中
      

  8.   

    select top 1 x.a,y.a,z.a from Test x,Test y,Test z where x.a<y.a and y.a<z.a and x.a+y.a+z.a=24
    order by newid()
      

  9.   

    1、laywarcraft(时间就像乳沟,挤挤还是有的) 、sunrisehy2003(黎明)、marco08(天道酬勤) :
    你们的办法似乎可以,但是你们为了达到“保證第3個數字在 @t 中”,方法也太龌龊了点(太拘泥于当前的表数据)
    ——就不能加上where 24-A.id-B.id in (select * from @t)?
    2、andy1995(拓狼 QQ群:16168607 MSN群:[email protected]) 方法也行
    3、还是谢谢各位了!不过要是我要得到“3个数和为24的所有组合呢?”又该何解?