在距离给定值最远的表中查找值

时间:2016-02-02 17:29:00

标签: sql sql-server sql-server-2008-r2

我需要从SQL Server 2008 R2表中查询数据。

表格:

 id    value
 1      0.63
 1      0.96
 5      1.15 
 5      1.2 

我需要一个id唯一的表,每个id的值与最大距离为1.示例:

 id    value
 1      0.63 // it far from 1 than 0.96
 5      1.2  // it is far from 1 than 1.15

我知道如何通过创建一个tabe来检查每个id ony的值。我需要用一个查询来完成它。

select distinct id value 
from table
group by id, max(abs(value -1))

谢谢!

3 个答案:

答案 0 :(得分:1)

一种方法使用row_number()

select id, value
from (select t.*, row_number() over (partition by id order by abs(value - 1)) as seqnum
      from t
where seqnum = 1;

可以将此作为聚合进行,但计算有点违反直觉:

select id,
       (case when max(abs(value - 1)) = max(value - 1) then max(value)
             else min(value)
        end) as value
from table t
group by id;

极值是最大值或最小值。您可以通过查看" sign"来确定这一点。最大值。

答案 1 :(得分:0)

使用Row_Number窗口功能执行此操作

select * from
(
select id, value, row_number()over(partition by id order by abs(value -1)) as rn
from table
) A
Where Rn = 1

答案 2 :(得分:0)

本质上与其他海报相同的答案,唉他们订购错误:

DECLARE @tt TABLE(id INT,value DECIMAL(28,2));
INSERT INTO @tt(id,value)VALUES(1,0.63),(1,0.96),(1,-0.25),(5,1.15),(5,1.2),(5,1.77);

;WITH cte AS (
    SELECT
        *,
        seqnr=ROW_NUMBER() OVER (PARTITION BY id ORDER BY ABS(value-1) DESC)
    FROM
        @tt
)
SELECT
    id,
    value
FROM    
    cte
WHERE
    seqnr=1;

结果:

+----+-------+
| id | value |
+----+-------+
|  1 | -0.25 |
|  5 | 1.77  |
+----+-------+