admin

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

sql

我尝试在执行以下命令后获得具有最高/最低编号的行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)

现在,idrow22,但应该是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)

如何根据最低的结果为每个结果获取正确的ID value


阅读 202

收藏
2021-05-10

共1个答案

admin

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

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 价值 姓名
1个 10 第1行
4 5 第2行

在这里,我使用minVal和Name自联接了表。

2021-05-10