小编典典

Haversine公式使用SQL Server查找最接近的场所-vb.net

sql

我正在从表单中获取邮政编码。然后,我可以将这些邮政编码转换为lng,lat坐标,因为这些存储在表中。

SELECT lng, lat from postcodeLngLat WHERE postcode = 'CV1'

我还有另一张桌子,上面存放着一些场馆的家具。

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

我要尝试做的是创建一个数据网格,该数据网格显示每个场所与邮政编码(在本例中为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


阅读 145

收藏
2021-03-23

共1个答案

小编典典

我认为您最好将其放入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
2021-03-23