1

我有两张桌子叫做hotelsand hotel locations。在hotels我的表中HotelId, hotelName。在hotelLocations我的表中HotelId, HotelNorthing, HotelEasting。是表HotelId中引用的外键HotelId,并且是保存酒店北距和东距值的 UTM 坐标。hotelsHotelNorthingHotelEasting

我想使用此数据查找彼此最近的 2 家酒店,并通过查询显示酒店表中的酒店名称和 ID 以及计算的距离。我以前尝试过各种交叉连接,但都失败了。我使用了毕达哥拉斯定理来计算酒店之间的距离,但我没有找到合适的查询结构。

4

1 回答 1

3

假设 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
于 2012-12-05T03:25:46.557 回答