1

我有一个如下表:

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

我该如何继续?任何帮助表示赞赏。

4

2 回答 2

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
于 2013-09-11T12:19:52.777 回答
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().

于 2013-09-11T12:20:40.613 回答