SQL Group By and min (MySQL)

前端 未结 3 1785
挽巷
挽巷 2020-12-07 01:41

I have the following SQL:

select code, distance from places;    

The output is below:

CODE    DISTANCE            LOCATION
         


        
3条回答
  •  我在风中等你
    2020-12-07 02:26

    You can try to do a nested lookup between the minimum grouping and the original table.

    This seems to do the trick

    SELECT MinPlaces.Code, MinPlaces.Distance, Places.Location 
    FROM Places INNER JOIN
    (
        SELECT Code, MIN(Distance) AS Distance
        FROM Places
        GROUP BY Code
        HAVING MIN(Distance) > 0 
    ) AS MinPlaces ON Places.Code = MinPlaces.Code AND Places.Distance = MinPlaces.Distance
    ORDER BY MinPlaces.Distance ASC
    

    UPDATE: Tested using the following:

    DECLARE @Places TABLE ( Code INT, Distance FLOAT, Location VARCHAR(50) )
    
    INSERT INTO @Places (Code, Distance, Location)
    VALUES
    (106, 386.895834130068, 'New York, NY'),
    (80, 2116.6747774121, 'Washington, DC'),
    (80, 2117.61925131453, 'Alexandria, VA'),
    (106, 2563.46708627407, 'Charlotte, NC')
    
    SELECT MinPlaces.Code, MinPlaces.Distance, P.Location 
    FROM @Places P INNER JOIN
    (
        SELECT Code, MIN(Distance) AS Distance
        FROM @Places
        GROUP BY Code
        HAVING MIN(Distance) > 0 
    ) AS MinPlaces ON P.Code = MinPlaces.Code AND P.Distance = MinPlaces.Distance
    ORDER BY MinPlaces.Distance ASC
    

    And this yields:

    enter image description here

提交回复
热议问题