Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

mysql - Get row with highest or lowest value from a GROUP BY

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 test;
+----+-------+------+
| id | value | name |
+----+-------+------+
|  1 |    10 | row1 |
|  2 |    12 | row2 |
|  3 |    10 | row2 |
|  4 |     5 | row2 |
+----+-------+------+
4 rows in set (0.00 sec)

To get the lowest value, I'll use MIN()

mysql> SELECT id, name, MIN(value) AS value FROM test GROUP BY name;
+----+------+-------+
| id | name | value |
+----+------+-------+
|  1 | row1 |    10 |
|  2 | row2 |     5 |
+----+------+-------+
2 rows in set (0.00 sec)

Now, the id row2 is 2, but it should be 4.

I also tried with a join:

mysql> SELECT t1.* FROM 
       (SELECT id, name, MIN(value) AS value 
          FROM test GROUP BY name) AS t1 
       INNER JOIN test AS t2 ON t1.id = t2.id;
+----+------+-------+
| id | name | value |
+----+------+-------+
|  1 | row1 |    10 |
|  2 | row2 |     5 |
+----+------+-------+
2 rows in set (0.00 sec)

How can I get the correct ID for each result based on what the lowest value is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...