有一个表的数据是这样的 
ID   Value 
1     10 
2     15 
3     10 
4     20 
5     12 
要求查询后的结果如下 
ID   Value   Average 
1     10           0 
2     15           0 
3     10           12.5 
4     20           12.5 
5     12           15 其中Average字段的值表示前两条记录的Value的 
平均值,1,2的值为0,表示他们前面不足两条记录。 
如何实现,请教高手,谢谢!

解决方案 »

  1.   

    select a.id, a.value
      , average = case when a.id<=2 then 0
            else (b.id+c.id)/2 end
    from tab a
    join tab b on b.id = a.id-1
    join tab c on c.id = a.id-2
      

  2.   

    上面那位大哥写错太多了吧。我重组一下。select a.id, a.value,case when a.id<=2 then 0 else (b.value+c.value)/2 end Average
    from ct a
    left join ct b on b.id = a.id-1
    left join ct c on c.id = a.id-2
    order by Id;
    还有不用left join前两行应该不会显示的。
      

  3.   

    是的,我太马虎了。
    sorry