首页 > 解决方案 > SQL获取最接近数字的值

问题描述

我需要从 Quantity 列中找到 Divide 列中每个数字的最接近的值,并将在这两个 Quantities 的 Value 列中找到的值。

示例:在 Divide 列中,5166 的值将最接近 Quantity 列的值 5000。为了避免多次使用这两个值,我需要将 5000 的值放在两个数字的值列中,如下例所示。另外,是否可以在没有循环的情况下执行此操作?

Quantity    Divide  Rank         Value
15500       5166    5            5000
1250        416     5            0
5000        1666    5            5000
12500       4166    4            0
164250      54750   3            0
5250        1750    3            0
6250        2083    3            0
12250       4083    3            0
1750        583     2            0
17000       5666    2            0
2500        833     2            0
11500       3833    2            0
1250        416     1            0

标签: sqlsql-server

解决方案


这里有几个答案,但它们都使用 ctes/complex 子查询。有一种更简单/更快的方法,只需进行几次自我加入和分组

https://www.db-fiddle.com/f/rM268EYMWuK7yQT3gwSbGE/0

select 
      min(min.quantity) as minQuantityOverDivide
    , t1.divide
    , max(max.quantity) as maxQuantityUnderDivide
    , case 
        when 
            (abs(t1.divide - coalesce(min(min.quantity),0)) 
            <
            abs(t1.divide - coalesce(max(max.quantity),0)))
        then max(max.quantity)
        else min(min.quantity) end as cloestQuantity

from t1
left join (select quantity from t1) min on min.quantity >= t1.divide
left join (select quantity from t1) max on max.quantity < t1.divide

group by    
    t1.divide

推荐阅读