2015-05-06 132 views
1

我收到了一個包含正數和負數的數字列表。如何找到最接近於零的det編號的記錄?如何返回最接近零的值

這個查詢

SELECT MIN(ABS(dNumber)) 
FROM myTable 

回報DET絕對值最小。不過,我想要返回有符號的值。

因此,如果myTable包含2條記錄;一個是dNumber = 2000,第二個是dNumber = -1000,我希望查詢返回-1000,而不是1000.

編輯: 忘了提及這個,它必須是一個集合函數作爲查詢的一部分與GROUP BY

SELECT Key1, Key2, 
    SUM(CASE WHEN /*condition1*/ THEN dNumber ELSE NULL END) AS 'Value1', 
    SUM(CASE WHEN /*condition2*/ THEN dNumber ELSE NULL END) AS 'Value2', 
    MIN(ABS(dNumber)...) AS 'ClosestToZeroAndSigned' 
FROM myTable 
/*joins*/ 
WHERE /*conditions*/ 
GROUP BY Key1, Key2 
+0

原來的職位與組大的查詢的一部分編輯 – hightow

+0

我注意到你的編輯和改進我的回答 – ASh

回答

4

一單機查詢

SELECT top 1 dNumber 
FROM myTable 
order by ABS(dNumber) 

II。通過

;with cte as 
(
    SELECT Key1, Key2, 
    SUM(CASE WHEN /*condition1*/ THEN dNumber ELSE NULL END) AS 'Value1', 
    SUM(CASE WHEN /*condition2*/ THEN dNumber ELSE NULL END) AS 'Value2', 
    -- max negative value 
    max(case when dNumber <= 0 then dNumber else null end) as Negative, 
    -- min positive value 
    min(case when dNumber > 0 then dNumber else null end) as Positive 
    FROM myTable 
    /*joins*/ 
    WHERE /*conditions*/ 
    GROUP BY Key1, Key2 
) 
select 
    Key1, Key2, Value1, Value2 
    Negative, Positive, 
    case when (abs(Negative) < Positive or Positive is null) then Negative else Positive end as 'ClosestToZeroAndSigned' 
from cte