【问题标题】:calculate min distance of each shop's location sql query计算每个商店位置sql查询的最小距离
【发布时间】:2020-02-12 05:03:09
【问题描述】:

我有一个表格,其中包含每个商店的 X、Y 坐标。我想找到彼此的最小距离。我的意思是最近的商店。

例如:(期望的输出)

Shop_ID      Nearest_Shop_ID 
Shop_1       Shop_5
Shop_2       Shop_8
Shop_3       Shop_4


Select SHOP_ID, Longtitude, Latitude From PARTNER_ADDRESSES
group by SHOP_ID, Longtitude, Latitude;

这是我的店铺坐标表;

SHOP_ID     LONGTITUDE  LATITUDE
38599       32.815282   39.882793
38613       25.965545   42.166315
38682       31.845157   37.419859
38686       34.027568   38.370871

我有一个公式可以计算两个位置之间的距离(使用纬度和经度)。这是公式;

(NVL(6387.7,0) * ACOS((sin(NVL(Latitude1,0) / 57.29577951) * SIN(NVL(Latitude2,0) / 57.29577951)) +
        (COS(NVL(Latitude1,0) / 57.29577951) * COS(NVL(Latitude2,0) / 57.29577951) *
         COS(NVL(Longtitude2,0) / 57.29577951 - NVL(Longtitude1,0)/ 57.29577951))))

Latitude1  : Shop 1's Latitude value
Longtitude1: Shop 1's Longtitude value

Latitude2  : Shop 2's Latitude value
Longtitude2: Shop 2's Longtitude value

是否可以编写这种sql来计算每个商店的距离并列出每个商店的最小距离值?

【问题讨论】:

  • 你的桌子有多大?性能有多重要?
  • 我的桌子上有 5000 家商店。性能对我们很重要。谢谢@GordonLinoff

标签: sql oracle latitude-longitude geo


【解决方案1】:

你可以使用交叉连接来做每家商店和每家商店,比如

select <distance formula> from shops as ashops cross join shops as bshops

从那里,您可以使用嵌套 SQL 从每个商店的最小距离中选择一个

【讨论】:

    【解决方案2】:

    我认为你可以使用cross join,然后使用row_number

    with distance1 as (
    select
    pa1.SHOP_ID as shop_id1, pa1.Longtitude longitude_1, pa1.Latitude latitude_1,
    pa2.SHOP_ID as shop_id2, pa2.Longtitude longitude_2, pa2.Latitude latitude_2,
    <your_distance_formula> as Distance
    from PARTNER_ADDRESSES pa1
    cross join PARTNER_ADDRESSES pa2
    where pa1.SHOP_ID <> pa2.SHOP_ID -- remove record where shops are the same
    )
    
    select *
    from (
    select *,
    row_number() over (partition by shop_id1 order by Distance) rn_distance
    from distance1
    ) 
    where rn_distance = 1
    

    【讨论】:

      【解决方案3】:

      您可以使用self joinanalytical function

      Select s1, s2 from
      (Select a1.shop_id as s1, a2.shop_id as s2,
      Row_number() 
      over (partition by a1.shop_id
        Order by <your_formula>) as rn
      From partner_adresses a1
      Join partner_adresses a2
      On (a1.shop_id <> a2.shop_id))
      Where rn = 1;
      

      干杯!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 2018-12-04
        相关资源
        最近更新 更多