假设 MS SQL 2008 或更高版本我会使用内置的地理类型:
insert into locations (name, location) values
('Hotel1', 'Point(138.58 -34.92)'),
('Hotel2', 'POINT(138.97 -34.78)'),
('Hotel3', 'POINT(138.00 -34.00)'),
('Hotel4', 'POINT(138.57 -34.01)'),
('Hotel5', 'POINT(138.50 -34.03)'),
('Hotel6', 'POINT(138.49 -34.04)'),
('Hotel7', 'POINT(138.88 -34.04)')
declare @StartLocation geography
select @StartLocation = location
from Locations
where name = 'Hotel1'
select location.STDistance(@StartLocation)
from locations
这将为您提供从 Hotel1 到所有其他酒店的距离,然后只需对列表进行排序并获得前 2 名即可。
编辑:从每家酒店计算到每家其他酒店:
create table locations
(
ID INT IDENTITY(1,1),
Name varchar(50),
Location geography
)
insert into locations (name, location) values
('Hotel1', 'Point(138.58 -34.92)'),
('Hotel2', 'POINT(138.59 -34.93)'),
('Hotel3', 'POINT(138.00 -34.00)'),
('Hotel4', 'POINT(138.57 -34.01)'),
('Hotel5', 'POINT(138.50 -34.03)'),
('Hotel6', 'POINT(138.49 -34.04)'),
('Hotel7', 'POINT(138.88 -34.04)')
select l1.name, l2.name, l1.location.STDistance(l2.Location)
FROM Locations l1
JOIN Locations l2 on l2.ID < l1.ID
编辑 2:将酒店名称拆分为单独的表格:
create table locationNames
(
ID INT IDENTITY(1,1),
Name VARCHAR(50)
)
insert into locationNames (Name) VALUES
('Hotel1'),
('Hotel2'),
('Hotel3'),
('Hotel4'),
('Hotel5'),
('Hotel6'),
('Hotel7')
create table locations
(
ID INT IDENTITY(1,1),
Location geography
)
insert into locations (location) values
('Point(138.58 -34.92)'),
('POINT(138.59 -34.93)'),
('POINT(138.00 -34.00)'),
('POINT(138.57 -34.01)'),
('POINT(138.50 -34.03)'),
('POINT(138.49 -34.04)'),
('POINT(138.88 -34.04)')
select ln1.Name, ln2.Name, l1.location.STDistance(l2.Location)
FROM Locations l1
JOIN Locations l2 on l2.ID < l1.ID
JOIN LocationNames ln1 on ln1.ID = l1.ID
JOIN LocationNames ln2 on ln2.ID = l2.ID