如何返回最接近零的值

时间:2015-05-06 12:26:27

标签: sql-server

我有一个带有数字列的表,其中包含正数和负数。如何找到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

1 个答案:

答案 0 :(得分:4)

予。独立查询

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

II。使用group by

的较大查询的一部分
;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