MS SQL 2008 以降を想定すると、組み込みの geography タイプを使用します。
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