Calculate distance between points using Long and Lat in SQL SERVER

I use the destination below

[BMAnalytics].[dbo].[EUACTIVESTORES]

And he has columns

[Store No]
[Lat]
[Long]

Can I use these columns to independently join the [Store No], so I have every Store to Store combination listed in the two columns called "Source" and "Target"

And then in the third column can I calculate the distance between the two?

I used the previous one earlier, but this only works for one point,

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

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

Ideally, I need the distance from each branch to each branch, etc.

Any recommendations are welcome.

+4
source share
2 answers

Here is a quick example of using Self Join

, , , , , , .

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]

enter image description here

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

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

:

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
+3

Source: https://habr.com/ru/post/1682935/


All Articles