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

How do I find the closest number across columns?

我有这个table:

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

我想派生一个新的列选择,指示最接近比较值的列:

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

选择是指单元格值最接近比较值的列。

我认为最简单的方法是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;

在平局的情况下,这 returns 任意最接近的列。

您也可以使用 case 表达式,但这会变得复杂。没有 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;

如果出现平局,这 returns 第一列。