Calculate distance between points using Long and Lat in SQL SERVER

梦想的初衷 提交于 2019-12-05 14:06:55

Here is a quick example using a Self Join

If you can, I would suggest adding a field to your source table which contains the Geography Point, and thus eliminate the need to calculate this value each time you run a query.

Example

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)

And then the calculation would be

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

FINAL QUERY LOOKS LIKE:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!