2015-05-06 95 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