我正在从表单中获取邮政编码。然后我可以将此邮政编码转换为 lng,lat 坐标,因为我将这些坐标存储在表中。SELECT lng, lat from postcodeLngLat WHERE postcode = 'CV1'
我有另一个表,用于存储一系列 field 的 lng,lat。SELECT v.lat, v.lng, v.name, p.lat, p.lng, p.postcode, 'HAVERSINE' AS distance FROM venuepostcodes v, postcodeLngLat p WHERE p.outcode = 'CB6' ORDER BY distance
我想要做的是创建一个数据网格,它显示每个 field 与邮政编码的距离(在这种情况下为 CV1)。我知道Haversine 公式应该做我想要实现的目标,但是我不知道应该从哪里开始将它合并到我的查询中。我认为公式需要放在我在上面的查询中放置 'HAVERSINE'
的位置。
有任何想法吗?
编辑 SELECT o.outcode AS lead_postcode, v.venue_name, 6371.0E * ( 2.0E *asin(case when 1.0E < (sqrt(square(sin(((RADIANS(CAST(o.lat AS FLOAT)))-(RADIANS(CAST(v.lat AS FLOAT))))/2.0E)) + (cos(RADIANS(CAST(v.lat AS FLOAT))) * cos(RADIANS(CAST(o.lat AS FLOAT))) * square(sin(((RADIANS(CAST(o.lng AS FLOAT)))-(RADIANS(CAST(v.lng AS FLOAT))))/2.0E))))) then 1.0E else (sqrt(square(sin(((RADIANS(CAST(o.lat AS FLOAT)))-(RADIANS(CAST(v.lat AS FLOAT))))/2.0E)) + (cos(RADIANS(CAST(v.lat AS FLOAT))) * cos(RADIANS(CAST(o.lat AS FLOAT))) * square(sin(((RADIANS(CAST(o.lng AS FLOAT)))-(RADIANS(CAST(v.lng AS FLOAT))))/2.0E))))) end )) AS distance FROM venuepostcodes v, outcodepostcodes o WHERE o.outcode = 'CB6' ORDER BY distance
最佳答案
我认为你最好把它放在一个 UDF 中并在你的查询中使用它:
SELECT v.lat, v.lng, v.name, p.lat, p.lng, p.postcode, udf_Haversine(v.lat, v.lng, p.lat, p.lng) AS distance FROM venuepostcodes v, postcodeLngLat p WHERE p.outcode = 'CB6' ORDER BY distance
create function dbo.udf_Haversine(@lat1 float, @long1 float, @lat2 float, @long2 float) returns float begin
declare @dlon float, @dlat float, @rlat1 float, @rlat2 float, @rlong1 float, @rlong2 float, @a float, @c float, @R float, @d float, @DtoR float
select @DtoR = 0.017453293
select @R = 3937 --3976
select
@rlat1 = @lat1 * @DtoR,
@rlong1 = @long1 * @DtoR,
@rlat2 = @lat2 * @DtoR,
@rlong2 = @long2 * @DtoR
select
@dlon = @rlong1 - @rlong2,
@dlat = @rlat1 - @rlat2
select @a = power(sin(@dlat/2), 2) + cos(@rlat1) * cos(@rlat2) * power(sin(@dlon/2), 2)
select @c = 2 * atn2(sqrt(@a), sqrt(1-@a))
select @d = @R * @c
return @d
end
关于sql - 使用 SQL Server 查找最近 field 的半正弦公式 - vb.net,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5362475/