2

我有这张桌子:

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

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

4

1 回答 1

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;

在平局的情况下,这将返回任意最近的列。

您也可以使用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;

如果出现平局,则返回第一列。

于 2019-11-18T16:13:21.357 回答