如何查找给定范围的最大记录

时间:2017-06-27 20:57:41

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

我有一组给定范围1-100101-10001。我想找到每个范围的最大记录。

输入:

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

输出:

Distance Rate
50       300
2000     2000
我正在考虑 select max(rate) from table group by或其他窗口函数。因为这个问题与其他类似的问题太接近了,所以我只找到了其他类似问题的解决方案,比如给定日期。

范围来自人类输入,但我可以为它创建一个表格。

1 个答案:

答案 0 :(得分:0)

只需使用group by

select (case when distance <= 100 then 'group 1'
             when distance <= 1000 then 'group 2'
             else '!?!'
        end) as range_group,
       max(rate)
from t
group by (case when distance <= 100 then 'group 1'
               when distance <= 1000 then 'group 2'
               else '!?!'
          end);
相关问题