SQL Group By and min (MySQL)

前端 未结 3 1778
挽巷
挽巷 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:30

    You did not say your DBMS. The following solutions are for SQL Server.

    WITH D AS (
       SELECT code, distance, location,
          Row_Number() OVER (PARTITION BY code ORDER BY distance) Seq
       FROM places
    )
    SELECT *
    FROM D
    WHERE Seq = 1
    

    If you have a table with unique Codes, and an index in your Places table on [Code, Distance] then a CROSS APPLY solution could be better:

    SELECT
       X.*
    FROM
       Codes C
       CROSS APPLY (
          SELECT TOP 1 *
          FROM Places P
          WHERE C.Code = P.Code
          ORDER BY P.Distance
       ) X
    

    I cannot work on a solution for mysql unti much later.

    P.S. You cannot rely on insertion order. Do not try!

提交回复
热议问题