SQL:选择两列减法的最小值,并选择min减法中使用的数字

时间:2015-01-26 17:41:58

标签: sql sql-server select min difference

我有两列,我想选择:价格,最小值abs。 Price和Strike之间的差异,以及与最小abs相对应的Strike。差异计算。我是SQL新手,如果这很容易,请原谅我。

Price   Strike
30.8    29
30.8    30
30.8    31
30.2    29
30.2    30
30.2    31

我想得到的答案是:

Price  Diff  Strike
30.8   .2    31
30.2   .2    30

我到目前为止的代码是:

Select min(price) as 'Price',
min(abs(price - Strike)) as 'Diff'
from Table
group by price

我不知道如何正确选择相应的警示。

谢天谢地

2 个答案:

答案 0 :(得分:4)

我将使用Window Function来执行此操作。

SELECT Price,
       Diff,
       Strike
FROM   (SELECT *,
               Abs(price - Strike) Diff,
               Row_number()OVER(partition BY price ORDER BY Abs(price - Strike) )rn
        FROM   Yourtable) a
WHERE  rn = 1 

或者,如果每个Abs(price - Strike)组的最小值为price,并且如果所有行都具有相同的最小值,则使用Dense_Rank

SELECT Price,
       Diff,
       Strike
FROM   (SELECT *,
               Abs(price - Strike) Diff,
               Dense_Rank()OVER(partition BY price ORDER BY Abs(price - Strike) )rn
        FROM   Yourtable) a
WHERE  rn = 1 

答案 1 :(得分:1)

执行此操作的最佳方法是通过窗口函数(特别是RANK()):

SELECT price, strike, difference
  FROM (
    SELECT price, strike, ABS(price - strike) AS difference
         , RANK() OVER ( ORDER BY ABS(price - strike) ) AS rn
      FROM mytable
) x
 WHERE x.rn = 1;

你也可以使用DENSE_RANK()(在这种情况下它不重要)。