Get row with highest or lowest value from a GROUP BY

后端 未结 1 1972
生来不讨喜
生来不讨喜 2020-12-16 12:23

I\'m trying to get the row with the highest/lowest number, after performing a GROUP BY:

Here is my test data

mysql> SELECT * FROM tes         


        
相关标签:
1条回答
  • 2020-12-16 12:51

    I think this is what you are trying to achieve:

    SELECT t.* FROM test t
    JOIN 
    ( SELECT Name, MIN(Value) minVal
      FROM test GROUP BY Name
    ) t2
    ON t.Value = t2.minVal AND t.Name = t2.Name;
    

    Output:

    ID VALUE NAME
    1 10 row1
    4 5 row2

    See this SQLFiddle

    • Demo with more values
    • Demo with duplicate values
    • Demo with removing duplicate values (using DISTINCT)

    Here I have self-joined the table with minVal and Name.

    0 讨论(0)
提交回复
热议问题