我得到了一个包含正数和负数的数字列的表格。如何找到 det 编号最接近于零的记录?
这个查询
SELECT MIN(ABS(dNumber))
FROM myTable
Run Code Online (Sandbox Code Playgroud)
返回 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
Run Code Online (Sandbox Code Playgroud)
一、单机查询
SELECT top 1 dNumber
FROM myTable
order by ABS(dNumber)
Run Code Online (Sandbox Code Playgroud)
二、使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
971 次 |
| 最近记录: |