select t_time,avg(t_value) as t_value from tablename a where t_value in (select top 10 t_value from tablename where t_time=a.t_time order by t_value) group by t_time

解决方案 »

  1.   


    为了简化入数,我把datetime类型改成了varchar:create function ts ( @t varchar(2) )
    returns int
    as
    begin
        declare @i int
        select @i=avg(i) from (select top 10 i from t where t=@t order by i desc) a
        return @i
    end
    gocreate table t (t varchar(2),i int)insert t select '1',1
    union select '1',2
    union select '1',3
    union select '1',4
    union select '1',5
    union select '1',6
    union select '1',7
    union select '1',8
    union select '1',9
    union select '1',12
    union select '1',22
    union select '1',32
    union select '1',42
    union select '1',52
    union select '1',62
    union select '1',72
    union select '1',2
    union select '1',82
    union select '1',92
    union select '1',2
    union select '12',2
    union select '12',22
    union select '12',23
    union select '12',24
    union select '12',25
    union select '12',26
    union select '12',27
    union select '12',28
    union select '12',29
    union select '12',20
    union select '12',926
    union select '12',927
    union select '12',928
    union select '12',929
    union select '12',920select t, dbo.ts(t)
    from t 
    group by tdrop table t
      

  2.   

    谢谢:zheninchangjiang!感觉好象行得通,偶试试~~~不过弱弱的问一下:你讲的更好的约束是指什么?呵呵~~~偶很菜的:))
      

  3.   

    请教:victorycyz
    如果我要的平均值不是前10位,而是前N(0,10];我这样改怎么好象不行?
    create function ts ( @t varchar(2),@n int )
    returns int
    as
    begin
        declare @i int
        select @i=avg(i) from (select top @n i from t where t=@t order by i desc) a
        return @i
    end
      

  4.   


    top 后面不允许跟变量的。