Get row with highest or lowest value from a GROUP BY(从 GROUP BY 中获取具有最高或最低值的行)
问题描述
在执行 GROUP BY
后,我正在尝试获取具有最高/最低编号的行:
I'm trying to get the row with the highest/lowest number, after performing a 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()
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)
现在,id row2
是 2
,但它应该是 4
.
Now, the id row2
is 2
, but it should be 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?
How can I get the correct ID for each result based on what the lowest value
is?
推荐答案
我认为这就是您要实现的目标:
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;
输出:
ID | VALUE | 姓名 |
---|---|---|
1 | 10 | row1 |
4 | 5 | row2 |
参见这个SQLFiddle
- 具有更多价值的演示
- 带有重复值的演示
- 删除重复值的演示(使用
DISTINCT
)
这里我用 minVal 和 Name 自行加入了表.
Here I have self-joined the table with minVal and Name.
这篇关于从 GROUP BY 中获取具有最高或最低值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 GROUP BY 中获取具有最高或最低值的行
基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01