Minimum distance and group by

折月煮酒 提交于 2019-12-13 04:45:13

问题


I'm trying to make a query which give the nearest shop from a city.

I've this table (The result of a query in fac recorded in temporary table)

id_Customer | id_Shop | distance
-------------------------------
1           | 1       | 10
1           | 2       | 30
1           | 3       | 100
2           | 3       | 150
2           | 2       | 300
2           | 1       | 400

I would have this result (The minimal distance)

id_Customer | id_Shop | distance
-------------------------------
1           | 1       | 10
2           | 3       | 150

How can I do this?


回答1:


Here is an excellent article in the official MySQL documentation:

Quote:

The Rows Holding the Group-wise Maximum of a Certain Column

Task: For each article, find the dealer or dealers with the most expensive price.

This problem can be solved with a subquery like this one:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article);

The preceding example uses a correlated subquery, which can be inefficient (see Section 13.2.10.7, “Correlated Subqueries”). Other possibilities for solving the problem are to use an uncorrelated subquery in the FROM clause or a LEFT JOIN.

Uncorrelated subquery:

SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
  SELECT article, MAX(price) AS price
  FROM shop
  GROUP BY article) AS s2
  ON s1.article = s2.article AND s1.price = s2.price;

LEFT JOIN:

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL;

The LEFT JOIN works on the basis that when s1.price is at its maximum value, there is no s2.price with a greater value and the s2 rows values will be NULL.




回答2:


select t.id_Customer, t.id_Shop, t.distance 
from your_table t
inner join 
(
   select id_Customer, min(distance) as m_dis
   from your_table
   group by id_Customer
) x on x.id_Customer = t.id_Customer and t.distance = x.m_dis


来源:https://stackoverflow.com/questions/18737678/minimum-distance-and-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!