如何计算(每个范围的平均值(平均值)?

时间:2017-06-27 21:22:55

标签: sql sql-server sql-server-2008

这是How to find max records for given range

的后续问题

我有几个人类输入范围,例如1-100101-10001。对于每个范围,我想计算rate - avg(rate for each range)

输入:

Distance Rate
10       5
25       200
50       300
1000     5
2000     2000

输出:

Distance rate - avg(rate for each range)
10       x
25       xx
50       xx
1000     xx
2000     xxx

1 个答案:

答案 0 :(得分:1)

您需要定义范围,然后使用窗口函数。这很简单:

select t.distance, t.rate, v.grp,
       (t.rate - avg(t.rate) over (partition by v.grp)) as deviation
from t outer apply
     (values (case when t.distance <= 100 then '1-100'
                   when t.distance <= 1000 then '101-1000'
                   else 'other'
              end)
     ) v(grp);