gpt4 book ai didi

sql - 如何在 SQL 连接中使用 lat/lng 半径进行选择

转载 作者:行者123 更新时间:2023-12-05 06:46:58 25 4
gpt4 key购买 nike

我有一个 SQL function使用它们的 lat/lng 坐标计算两点之间的距离。使用此功能,我可以根据给定点的距离从大型集合(GEOCODES 表)中筛选出一组位置,如下所示:

DECLARE @LAT1 float, @LNG1 float,
SET @LAT1 = '34.169540'
SET @LNG1 = '-92.590990'

SELECT E.* FROM GEOCODES E
WHERE dbo.fnGetDistance(E.lat, E.lng, @LAT1, @LNG1, 'miles') < '20'

我有第二个表 (GEOMILES),其中点之间的距离为:

LOCATION1  | STATE1  |  LOCATION2  |  STATE2  | DISTANCE
-----------+---------+-------------+----------+---------
New York | NY | Boston | MA | 220

我想要实现的是一个 SELECT 查询,如果出发点在纽约 20 英里以内,而到达点在波士顿 20 英里以内,则该查询返回 220 的距离。到目前为止,我有这个,但是当我通过手动检查 lat/lng 点等加起来时,它什么也没有返回。非常感谢任何帮助!

DECLARE @FROM_LOC VARCHAR(100), @FROM_STA VARCHAR(2), @TO_LOC VARCHAR(100), @TO_STA VARCHAR(2)

SET @FROM_LOC = 'NEWARK'
SET @FROM_STA = 'NJ'

SET @TO_LOC = 'MEDFORD'
SET @TO_STA = 'MA'

SELECT G.DIST FROM GEOMILES G, GEOCODES E
JOIN GEOCODES C ON C.asciiname = @FROM_LOC AND C.admin1 = @FROM_STA
JOIN GEOCODES D ON D.asciiname = @TO_LOC AND D.admin1 = @TO_STA
WHERE dbo.fnGetDistance(E.lat, E.lng, C.lat, C.lng, 'miles') < '20'
AND dbo.fnGetDistance(E.lat, E.lng, D.lat, D.lng, 'miles') < '20'

最佳答案

我认为这就是您所追求的(使用您的表结构)。 . .

SELECT G.DIST
FROM GEOMILES G
, GEOCODES F --from airport
, GEOCODES E --to airport
, GEOCODES C --from location
, GEOCODES D --to location

WHERE C.asciiname = @FROM_LOC
AND C.admin1 = @FROM_STA

AND D.asciiname = @TO_LOC
AND D.admin1 = @TO_STA

AND dbo.fnGetDistance(F.lat, F.lng, C.lat, C.lng, 'miles') < 20
AND dbo.fnGetDistance(E.lat, E.lng, D.lat, D.lng, 'miles') < 20

and G.Location1 = F.asciiname
and G.Location2 = E.asciiname
and G.State1 = F.admin1
and G.State2 = E.admin1

备用版本(我认为这会表现得更好)

SELECT G.DIST
FROM GEOMILES G
inner join
(
select fromAirport.asciiname
, fromAirport.admin1
from GeoCodes fromAirport
where exists
(
select top 1 1
from GeoCodes fromLocation
where fromLocation.asciiname = @FROM_LOC
and fromLocation.admin1 = @FROM_STA
and dbo.fnGetDistance(fromLocation.lat, fromLocation.lng, fromAirport.lat, fromAirport.lng, 'miles') < 20
)
) fromA
on G.Location1 = fromA.asciiname
and G.State1 = fromA.admin1
inner join
(
select toAirport.asciiname
, toAirport.admin1
from GeoCodes toAirport
where exists
(
select top 1 1
from GeoCodes toLocation
where toLocation.asciiname = @TO_LOC
and toLocation.admin1 = @TO_STA
and dbo.fnGetDistance(toLocation.lat, toLocation.lng, toAirport.lat, toAirport.lng, 'miles') < 20
)
) toA
on G.Location1 = toA.asciiname
and G.State1 = toA.admin1

关于sql - 如何在 SQL 连接中使用 lat/lng 半径进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com