我正在使用以下目的地
[BMAnalytics].[dbo].[EUACTIVESTORES]
它有列
[Store No]
[Lat]
[Long]
我可以使用这些列自行加入[Store No],因此我将Store to Store的每个组合列在两列中,称为“Source”& '目标'
然后在第三列中可以计算两者之间的距离吗?
我之前使用过以下内容,但这仅适用于单点指向,
DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'
SELECT (@source.STDistance(@target))/1000
理想情况下,我希望从每个分支到每个分支的距离等。
欢迎任何指导
答案 0 :(得分:3)
以下是使用自我加入的快速示例
如果可以,我建议在源表中添加一个包含地理点的字段,这样就无需在每次运行查询时计算此值。
示例强>
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]
<强>返回强>
编辑如果您可以添加地理字段
Update YourTable Set GeoPoint = GEOGRAPHY::Point([Lat], [Lng], 4326)
然后计算
,Meters = A.GeoPoint.STDistance(B.GeoPoint)
答案 1 :(得分: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