gpt4 book ai didi

SQL Server 计算两组纬度/经度列之间的距离

转载 作者:行者123 更新时间:2023-12-04 03:09:45 25 4
gpt4 key购买 nike

我正在尝试计算距给定邮政编码最近的气象站。我有气象站的经纬度数据和邮政编码。我也有一种方法来计算 2 点的距离( here )。我正在寻找的是一种创建具有多个实例距离的列的方法。

StationNum  lat     lon     Zip     lat      lon   distance
123 34.66 98.32 12345 33.78 91.91 ???
456 33.03 96.8 23456 35.23 92.23 ???
789 32.29 96.85 34567 33.09 92.68 ???

有没有办法做到这一点,还是我需要手工写出数学?

最佳答案

使用 GEOGRAPHY 类型

您有重复的字段名称,因此我将它们重命名为 Lat1/Lon1 和 Lat2/Lon2。如果这是连接,请添加别名 a.lat/a.lon b.lat/b.lon。

示例

Declare @YourTable Table ([StationNum] varchar(50),[lat1] float,[lon1] float,[Zip] varchar(50),[lat2] float,[lon2] float)
Insert Into @YourTable Values
(123,34.66,98.32,12345,33.78,91.91)
,(456,33.03,96.8,23456,35.23,92.23)
,(789,32.29,96.85,34567,33.09,92.68)

Select *
,InMeters = GEOGRAPHY::Point([Lat1], [Lon1], 4326).STDistance(GEOGRAPHY::Point([Lat2], [Lon2], 4326))
,InMiles = GEOGRAPHY::Point([Lat1], [Lon1], 4326).STDistance(GEOGRAPHY::Point([Lat2], [Lon2], 4326)) / 1609.344
from @YourTable

返回

enter image description here

Edit - For your consideration



考虑向源表添加地理字段。这将消除多余的 GEOGRAPHY::Point() 函数调用
Update YourTable Set GeoPoint = GEOGRAPHY::Point([Lat], [Lon], 4326)

那么距离的计算就是
  ,InMeters  = A.GeoPoint.STDistance(B.GeoPoint) 
,InMiles = A.GeoPoint.STDistance(B.GeoPoint) / 1609.344

关于SQL Server 计算两组纬度/经度列之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46204513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com