-1

I have the following SQL in MySQL DB:

select code, distance from locations;    

The output is below:

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

I want to be able to just get a single code and the closest distance. So I want it to return this:

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

I originally had something like this:

SELECT code, min(distance), location
GROUP BY code
HAVING distance > 0 
ORDER BY distance ASC
3
  • Repeated stackoverflow.com/questions/11683712/sql-group-by-and-min Commented Jul 27, 2012 at 8:32
  • really ? select code, distance from locations; showed that output ? Commented Jul 27, 2012 at 8:33
  • @hussainnaghri, no idea what you're saying Commented Jul 27, 2012 at 8:36

3 Answers 3

0

try this:

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 
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

what if 2 codes have the exact same location, as i need all codes too?
This will lead to error. You need to include distinace in group by clause which will give different result
0

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

1 Comment

nope this doesn't work, you can still get locations that don't match the min distance because of the group by

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.