Reputation: 1040
I am using the below destination
[BMAnalytics].[dbo].[EUACTIVESTORES]
And it has columns
[Store No]
[Lat]
[Long]
Can I use these columns to self Join the [Store No] so I have each combination of Store to Store listed in two columns, called 'Source' & 'Target'
And then in a third column is it possible to calculate the distance between the two?
I have used the below previously but this only works for one single point to point,
DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'
SELECT (@source.STDistance(@target))/1000
Ideally, i'd like the distance from each branch to each branch etc.
Any guidance is welcome
Upvotes: 4
Views: 10230
Reputation: 1040
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
Upvotes: 3
Reputation: 82010
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)
Upvotes: 3