使用 T-SQL 比较两列之间的纬度和经度之间的距离

Comparing distance between Latitude and longitude between two columns using T-SQL

大家好,我正在尝试使用 MSSQL 中的地理数据比较客户端与其各自服务器之间的距离。

我能够成功比较两点之间的距离。 但是,仅显示最后一个条目的距离。

这是我正在使用的查询:

Declare @locations1 GEOGRAPHY;
Declare @locations2 GEOGRAPHY;
Declare @ServerID int;

SELECT @locations1 = GeoLoc from [TestDb].[dbo].[Locations] where IsClient =1;
SELECT @ServerID = ServerID from [TestDb].dbo.Locations where IsClient=1; 
SELECT @locations2 = GeoLoc from [TestDb].[dbo].[Locations] where IsClient =0 AND id=@ServerID ;

select @locations1.STDistance(@locations2)/1000 As [Distance in KM]

我相信上述查询的工作原理如下:

locations1 - 具有 IsClient 为 True 的列的地理位置。
ServerId - 具有 IsClient 为 True 的列的 ServerID。
locations2 - 具有 IsClient 为 0 的列的 GeoLocation 和 上面查询得到的 ServerId 与机器的 id 相匹配。

所以,
locations1 必须具有客户端的地理位置。
locations2 必须具有相应服务器的 GeoLocation。

我的Table设计:

当我比较时,我得到了正确的结果,但只有 table 中最后一个客户端和服务器条目之间的距离。 未显示任何其他条目的距离。

如何获取所有条目的距离? 需要帮助:)。 谢谢。

看起来您需要进行自连接,为此您始终需要 'alias' table 名称。像

SELECT l1.id,l2.id,l1.serverid, l1.geoloc.STDistance(l2.geoloc)/1000.0 As [Distance in KM] FROM
       [TestDb].[dbo].[Locations] l1 JOIN
       [TestDb].[dbo].[Locations] l2
            ON L1.IsClient = 1 AND L2.isClient = 0 AND L2.id = L1.ServerId

这样,对于每个客户端,就可以加入其服务器记录,如 l1.ServerId

所定义
  • l1 是左手 table,l2 是右手 table。

l1 和 l2 是 'aliases' 你的单身 table