2016-02-02 57 views
3

我需要從SQL Server 2008 R2表中查詢數據。查找距離給定值最遠的表中的值

表:

id value 
1  0.63 
1  0.96 
5  1.15 
5  1.2 

我需要ID唯一,從1例具有最大距離的表和每個ID值:

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的值。我需要用一個查詢來完成。

select distinct id value 
from table 
group by id, max(abs(value -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 
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; 

極值可以是最大或最小的價值。您可以通過查看最大值的「符號」來確定這一點。

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 | 
+----+-------+ 
相關問題