2016-09-28 81 views
0

SQL距离计算这可能是一个克隆问题,但我搜索的其他答案没有任何意义。我仍然在学习SQL,所以如果你能指导我完成这个过程,我将不胜感激。提前致谢。1点和其他任何其他

所以问题是:我有这个表格(其中有更多的数据),我需要得到最远离菲乌米奇诺机场的机场名称(这意味着我只有1组经度和纬度数据),我必须用距离函数来做。 Sql table

+0

? – anakic

+0

你能告诉我们你已经尝试了什么,并解释它为什么没有解决你的问题? – dfundako

+0

我删除了不兼容的数据库标签。为您正在使用的数据库添加一个。 –

回答

0

无论距离函数使用的是(用于短距离在数千里简单的直线毕达哥拉斯,或者大圆公式任何东西),

Select * from table 
where [DistanceFunction] 
     (Latitude, Longitude, FiumicinoLatitude, FiumicinoLongitude) = 
    (Select Max([DistanceFunction] 
     (Latitude, Longitude, FiumicinoLatitude, FiumicinoLongitude)) 
     From table) 

,如果你需要找到机场最远从(并不总是菲乌米奇诺)的一些任意的机场,那么,假设@code是任意机场机场代码:

Select * from table t 
    join table r on r.code = @code 
where [DistanceFunction] 
     (t.Latitude, t.Longitude, r.Latitude, r.Longitude) = 
    (Select Max([DistanceFunction] 
     (Latitude, Longitude, r.Latitude, r.Longitude)) 
3

只要你可以下面的SQL查询运行

SELECT *, (3959 * acos(cos(radians(37)) * cos(radians(lat)) * cos(radians(lng) - radians(-122)) + sin(radians(37)) * sin(radians(lat)))) AS distance FROM table_name;

其中;

要按公里而非英里搜索距离,与6371.

取代3959是你的输入纬度

-122是你输入的经度

LAT是表其中包含机场纬度列名值

LNG是包含机场经度值表的列名

更多细节回答:Creating a store locator

0

SQL SERVER

,如果你正在努力寻找从每个机场最远的一个,您将需要一个函数。但既然你说FCO,我就是为FCO做的。

您正在使用哪种类型的数据库
--temp table for testing 

select 'FCO' as code, 'Fiumicino' as name, 'Rome' as city, 'Italy' as country, 41.7851 as latitude, 12.8903 as longitude into #airports 
union all 
select 'VCE', 'Marco Polo','Venice','Italy',45.5048,12.3396 
union all 
select 'NAP', 'capodichino','Naples','Italy',40.8830,14.2866 
union all 
select 'CDG', 'Charles de Gaulle','Paris','France',49.0097,2.5479 

--create a point from your LAT/LON 
with cte as(
select 
    *, 
    geography::Point(latitude,longitude,4326) as Point --WGS 84 datum 
from #airports), 

--Get the distance from your airport of interest and all others. 
cteDistance as(
select 
    *, 
    Point.STDistance((select Point from cte where code = 'FCO')) as MetersToFiuminico 
from cte) 

--this is the one that's furthest away. Remove the inner join to see them all 
select d.* 
from 
    cteDistance d 
    inner join(select max(MetersToFiuminico) as m from cteDistance where MetersToFiuminico > 0) d2 on d.MetersToFiuminico = d2.m