我想我理解这个问题。对于每个价格,您都试图根据距离和位置分配最近的商店。
该方法从加入职位和商店开始。然后它计算位置和距离之间的差异——这似乎是您正在使用的度量。每个价格 ID 将出现两次(每个商店一次)。使用窗口函数,它计算每个 id 的最小差异。
有了这个信息,查询可以确定哪个是最近的商店。此版本返回价格,而不是最低价格的 id。这是最终的未经测试的查询:
select id_prod_ty,
MIN(case when diff = minDiff then price) as price_low,
MAX(case when diff = minDiff then price) as price_high,
s.id_shop
from (select p.id_prod_ty,
s.id_shop,
p.price,
(p.distance - s.position) as diff,
MIN(p.distance - s.position) over (partition by p.id) as minDiff
from products p join
shops s
on p.id_prod_ty = s.id_prod_ty
) ps
group by id_prod_ty, id_shop
这是一个获取 id 的变体。它使用窗口函数来查找最低和最高价格,然后将价格与这些值进行比较以获取 id:
select id_prod_ty,
MIN(minPrice) as price_low,
MIN(case when price = minPrice then id end) id_price_low,
MAX(maxprice) as price_high,
MIN(case when price = maxPrice then id end) id_price_high,
id_shop
from (select *,
MIN(IsThisShopPrice) over (partition by id_prod_ty, id_shop) as minPrice,
MIN(IsThisShopPrice) over (partition by id_prod_ty, id_shop) as maxPrice,
from (select p.id_prod_ty, s.id_shop, p.price, p.id,
(p.distance - s.position) as diff,
(case when (p.distance - s.position) = MIN(p.distance - s.position) over (partition by p.id)
then 'Y'
else 'N'
end) as IsThisShop
(case when (p.distance - s.position) = MIN(p.distance - s.position) over (partition by p.id)
then price
end) as IsThisShopPrice
from products p join
shops s
on p.id_prod_ty = s.id_prod_ty
) ps
) ps
group by id_prod_ty, id_shop