我有一张这样的桌子:
| Key | Value | Message |
|-----|-------|---------|
| a | 1 | xx |
| a | 2 | yy |
| b | 5 | mm |
| b | 4 | nn |我想按键对数据进行分组,得到每组的最小值,以及相关的消息。预计结果将是:
| Key | Value | Message |
|-----|-------|---------|
| a | 1 | xx |
| b | 4 | nn |我使用的是MySQL 5.7。这样做有可能吗?
发布于 2020-01-15 18:00:20
你可以试试下面的-
select * from tablename a
where value = (select min(value) from tablename b where a.key=b.key)发布于 2020-01-15 18:00:30
您可以使用row_number():
select t.*
from (select t.*, row_number() over (partition by key order by value) as seq
from table t
) t
where seq = 1;如果排名函数不支持,也可以使用相关subquery:
select t.*
from table t
where t.value = (select min(t1.value) from table t1 where t1.key = t.key);发布于 2020-01-15 18:02:56
在MySQL 5.7或更早版本中,处理此问题的规范方法是连接到子查询,该子查询为每个键查找最小值:
SELECT t1.`Key`, t1.`Value`, t1.Message
FROM yourTable t1
INNER JOIN
(
SELECT `Key`, MIN(`Value`) AS min_value
FROM yourTable
GROUP BY `Key`
) t2
ON t1.`Key` = t2.`Key` AND t1.`Value` = t2.min_value
ORDER BY
t1.`Key`;请尽量避免使用保留的SQL关键字命名列和其他数据库对象,例如Key和Value。您可以考虑是否需要在MySQL查询中键入反标记作为反模式。
https://stackoverflow.com/questions/59748968
复制相似问题