要求随机取3条记录.要求这3条记录的平均值在5到8之间.......
随机取3条可以写..现在考虑是取3条出来,判断其平均值,
如果符合则输出,8符合则重新取..直到符合...问题是.需要建1临时个表存一下取出的3条记录不?
....
有别的思路更好~~谢谢。.

解决方案 »

  1.   

    大概这样吧declare @flag int
    set @flag = 20  -- 尝试20次
    while @flag > 0
    begin
        if object_id('tempdb..#t') is not null
            drop table #t
        select top 3 * into #t from tb order by newid()
        if (select avg(计算列) from #t) between 5 and 8
            set @flag = 0
        set @flag = @flag - 1
    end
    if @flag = -1
        select * from #t
    else
        raiserror('没有满足条件的记录', 16, 1)
      

  2.   

    写是好写,但估计很难出数据。
    set nocount ondeclare @t int
    declare @f float
    set @t=1
    while @t<21
    begin
    select id into #t from table1 order by newid()
    set @f = (select avg(id) from #t)
    if @f between 5 and 8
             break
    set @t=@t + 1
    drop table #t
    end
    if @t < 21
    select * from #t
    else
    select ''
      

  3.   

    select top 1 第一个ID=a.id,第二个ID=b.id,第三个ID=c.id,平均值=(a.id+b.id+c.id)/3 from table1 a join table1 b on 1=1 join table1 c on 1=1
    where a.id<>b.id and b.id<>c.id and a.id<25 and b.id<25 and c.id<25
    group by a.id,b.id,c.id
    having sum(a.id+b.id+c.id)/3 between 5 and 8
    order by newid()
      

  4.   

    懒猫写的木看懂.....来个解释解释的。..谢谢zjcxc
      

  5.   

    select 第一个ID=a.id,第二个ID=b.id,第三个ID=c.id,平均值=(a.id+b.id+c.id)/3 from table1 a join table1 b on 1=1 join table1 c on 1=1
    where a.id<>b.id and b.id<>c.id and a.id<25 and b.id<25 and c.id<25
    group by a.id,b.id,c.id
    having sum(a.id+b.id+c.id)/3 between 5 and 8
    --这样可以遍历在table1表符合条件的所有组合,然后在这个结果中取其中一条即可:
    select top 1 第一个ID=a.id,第二个ID=b.id,第三个ID=c.id,平均值=(a.id+b.id+c.id)/3 from table1 a join table1 b on 1=1 join table1 c on 1=1
    where a.id<>b.id and b.id<>c.id and a.id<25 and b.id<25 and c.id<25
    group by a.id,b.id,c.id
    having sum(a.id+b.id+c.id)/3 between 5 and 8
    order by newid()
    --order by newid()随机排序,top 1取随机排序的第一条·!