在 SQL 服务器中使用 Long 和 Lat 计算点之间的距离

Calculate distance between points using Long and Lat in SQL SERVER

我正在使用以下目的地

[BMAnalytics].[dbo].[EUACTIVESTORES]

它有列

[Store No]
[Lat]
[Long]

我可以使用这些列自己加入 [Store No] 所以我将每个 Store to Store 组合列在两列中,称为 'Source' & 'Target'

然后在第三列中是否可以计算两者之间的距离?

我以前用过下面的,但这只适用于单点对点,

DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'

SELECT (@source.STDistance(@target))/1000

理想情况下,我想要每个分支到每个分支的距离等等

欢迎任何指导

这是一个使用自连接的简单示例

如果可以,我建议在源 table 中添加一个包含地理点的字段,这样就无需在每次 运行 查询时计算该值。

例子

Declare @YourTable table ([Store No] int,Lat float,Lng float)
Insert Into @YourTable values
 (1,-8.157908, -34.931675)
,(2,-8.164891, -34.919033)  
,(3,-8.159999, -34.939999)  

Select [From Store] = A.[Store No]
      ,[To Store]   = B.[Store No]
      ,Meters       = GEOGRAPHY::Point(A.[Lat], A.[Lng], 4326).STDistance(GEOGRAPHY::Point(B.[Lat], B.[Lng], 4326))
 From  @YourTable A
 Join @YourTable B on A.[Store No]<>B.[Store No]

Returns

EDIT If you can add a Geography Field

Update YourTable Set GeoPoint = GEOGRAPHY::Point([Lat], [Lng], 4326)

然后计算将是

,Meters = A.GeoPoint.STDistance(B.GeoPoint)

最终查询看起来像:

SELECT
      A.[STORE NO] AS 'SOURCE'
      ,B.[STORE NO] AS 'TARGET'
      ,CONVERT(DECIMAL(6,2),(((GEOGRAPHY::Point(A.[Lat], A.[Long], 4326).STDistance(GEOGRAPHY::Point(B.[Lat], B.[Long], 4326)))/1000)/8)*5) AS 'MILES'

FROM
      [bhxsql2014-dev].[BMAnalytics].[dbo].[EUACTIVESTORES] A
JOIN
      [bhxsql2014-dev].[BMAnalytics].[dbo].[EUACTIVESTORES] B on A.[Store No]<>B.[Store No]

WHERE 
         A.LAT        IS NOT NULL
     AND A.[STORE NO] IS NOT NULL
     AND B.LAT        IS NOT NULL
     AND B.[STORE NO] IS NOT NULL