从交叉联接的最少行中选择其他属性

时间:2018-10-04 01:57:40

标签: sql postgresql

我正在编写一个查询,该查询将许多位置与公交车站列表连接起来,以便确定距公共公交车站的最小距离。使用查询非常简单:

select
  location.id,
  MIN(
    ST_distance_sphere(
      ST_MakePoint(
        transit.latitude,
        transit.longitude
      ),
      ST_MakePoint(
        cast(locations.latitude as double precision),
        cast(locations.longitude as double precision)
      )
    )
  ) as meters_from_nearest_stop,
from public.transit_stops transit
cross join public.locations locations
group by 1

但是,这不能天真地给我最小距离的位置,而只是最小距离。如何修改此设置,以便以最小的距离返回行中的其他属性?

产生的交叉联接相当大,因此性能很重要。

1 个答案:

答案 0 :(得分:0)

这是通过row_number()函数完成的,如下所示:

select *, 
    row_number() over (partition by location.id order by meters_from_nearest_stop) as closest
from (
    select
      location.id,
      transit.id,
      ST_distance_sphere(
          ST_MakePoint(
            transit.latitude,
            transit.longitude
          ),
          ST_MakePoint(
            cast(locations.latitude as double precision),
            cast(locations.longitude as double precision)
          )
        )
      as meters_from_nearest_stop,
    from public.transit_stops transit
    cross join public.locations locations
) q
where closest=1