简体   繁体   English

如何在列中找到最接近的数字?

[英]How do I find the closest number across columns?

I have this table:我有这张桌子:

col_1 | col_2 | col_3 | compare
------+-------+-------+--------
 1.1  | 2.1   | 3.1   | 2
------+-------+-------+--------
 10   | 9     | 1     | 15

I want to derive a new column choice indicating the column closest to the compare value:我想派生一个新的列选择,指示最接近比较值的列:

col_1 | col_2 | col_3 | compare | choice
------+-------+-------+---------+-------
 1.1  | 2.1   | 3.1   | 2       | col_2
------+-------+-------+---------+-------
 10   | 9     | 1     | 15      | col_1

Choice refers to the column where cell value is closest to the compare value.选择是指单元格值最接近比较值的列。

I think the simplest method is apply :我认为最简单的方法是apply

select t.*, v.which as choice
from t cross apply
     (select top (1) v.*
      from (values ('col_1', col_1), ('col_2', col_2), ('col_3', col_3)
           ) v(which, val)
      order by abs(v.val - t.compare)
     ) v;

In the event of ties, this returns an arbitrary closest column.在平局的情况下,这将返回任意最近的列。

You can also use case expressions, but that gets complicated.您也可以使用case表达式,但这会变得复杂。 With no NULL values:没有NULL值:

select t.*,
       (case when abs(compare - col_1) <= abs(compare - col_3) and
                  abs(compare - col_1) <= abs(compare - col_3)
             then 'col_1'
             when abs(compare - col_2) <= abs(compare - col_3)
             then 'col_2'
             else 'col_3'
         end) as choice
from t;

In the event of ties, this returns the first column.如果出现平局,则返回第一列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM