从另一个位置获取具有最大距离的位置

时间:2013-09-11 12:14:16

标签: sql sql-server tsql

我有一张如下表:

Create table Distance
(Loc1ID int not null,
Loc2ID int not null,
Distance int not null)

Insert into Distance values(7 ,8023989 ,1)
Insert into Distance values(11 ,3705843 ,1)
Insert into Distance values(14 ,3700170 ,4)
Insert into Distance values(23 ,1353297 ,5)
Insert into Distance values(23 ,1491303 ,21)
Insert into Distance values(32 ,12514 ,74)
Insert into Distance values(32 ,507545 ,25)
Insert into Distance values(75 ,7971270 ,2)
Insert into Distance values(75 ,4473476 ,1)
Insert into Distance values(75 ,3280411 ,6)
Insert into Distance values(79 ,7100087 ,7)
Insert into Distance values(81 ,7986762 ,2)
Insert into Distance values(84 ,5034 ,31)
Insert into Distance values(84 ,3672346 ,3)

我想知道与Loc1ID有最大距离的位置。我需要以下格式的o / p。所以,预期的输出将是

Loc1ID    Loc2ID    Distance

7         8023989   1
11        3705843   1
14        3700170   4
23        1491303   21
32        12514     74
75        3280411   6
79        7100087   7
81        7986762   2
84        5034      31

我尝试了以下查询,但它只给了我一条记录。

select top 1 Loc1ID, Loc2ID, max(distance) as Distance from Distance
group by Loc1ID,Loc2ID
order by max(distance) desc

我该怎么办?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:4)

select Loc1ID, Loc2ID, distance from  
(select Loc1ID, Loc2ID, distance, 
rank() over(partition by Loc1ID order by distance desc) rn
from DISTANCE) a where rn =1

答案 1 :(得分:1)

对于每个Loc1ID,您需要具有最大距离的Loc2ID。为此,您需要使用row_number()

select d.Loc1ID, d.Loc2ID, d.distance
from (select d.*, row_number() over (partition by Loc1ID order by distance desc) as seqnum
      from Distance d
     ) d
where seqnum = 1;

如果在重复时需要多行,请使用dense_rank()代替row_number()