获取GROUP BY中具有最高或最低值的行

时间:2013-06-04 04:53:38

标签: mysql sql group-by

执行GROUP BY后,我正在尝试获取最高/最低编号的行:

这是我的测试数据

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)

要获得最低价值,我会使用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)

现在,ID row22,但应为4

我也试过加入:

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)

如何根据最低value是什么来获取每个结果的正确ID?

1 个答案:

答案 0 :(得分:30)

我认为这是你想要实现的目标:

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;

输出:

╔════╦═══════╦══════╗
║ ID ║ VALUE ║ NAME ║
╠════╬═══════╬══════╣
║  1 ║    10 ║ row1 ║
║  4 ║     5 ║ row2 ║
╚════╩═══════╩══════╝

请参阅this SQLFiddle

这里我用minVal和Name自行加入了表格。