MySQL中的SQL Group By和Min

时间:2012-07-27 08:28:47

标签: mysql sql group-by min

我在MySQL DB中有以下SQL:

select code, distance from locations;    

输出如下:

CODE    DISTANCE            LOCATION
106     386.895834130068    New York, NY
80      2116.6747774121     Washington, DC
80      2117.61925131453    Alexandria, VA
106     2563.46708627407    Charlotte, NC
106     2030.5845606766     Atalanta, GA

我希望能够获得单个代码和最近的距离。所以我希望它能归还:

CODE    DISTANCE            LOCATION
106     386.895834130068    New York, NY
80      2116.6747774121     Washington, DC

我最初有这样的事情:

SELECT code, min(distance), location
GROUP BY code
HAVING distance > 0 
ORDER BY distance ASC

3 个答案:

答案 0 :(得分:0)

  SELECT code, min(distance), location
GROUP BY code,location
  HAVING distance =min(distance)

答案 1 :(得分:0)

试试这个:

select L.* from (
    SELECT code, min(distance) as min_distance 
    from places
    GROUP BY code)a
join places L
on L.CODE=a.CODE
and L.DISTANCE=a.min_distance 

答案 2 :(得分:0)

SELECT code, distance, location FROM locations GROUP BY code HAVING distance > 0
ORDER BY distance ASC LIMIT 1