mysql - 按类别显示 MySQL 8 中的前 N ​​个分数,不重复

标签 mysql group-by mysql-8.0

我在 MySQL 8.0.15 中有下表:

CREATE TABLE golf_scores (person TEXT, score INT);
INSERT INTO golf_scores VALUES ('Angela', 40),('Angela', 45),('Angela', 55),('Peter',45),('Peter',55),('Rachel', 65),('Rachel',75),('Jeff',75);

SELECT * FROM golf_scores;
+--------+-------+
| person | score |
+--------+-------+
| Angela |    40 |
| Angela |    45 |
| Angela |    55 |
| Peter  |    45 |
| Peter  |    55 |
| Rachel |    65 |
| Rachel |    75 |
| Jeff   |    75 |
+--------+-------+

我正在尝试获得以下前 3 名分数:

SELECT * FROM golf_scores;
+--------+-------+
| person | score |
+--------+-------+
| Angela |    40 |
| Peter  |    45 |
| Rachel |    65 |
+--------+-------+

换句话说,我想要最好(最低)的 3 高尔夫得分,而不是每个人都重复。我不担心领带;我仍然想要三个结果。

我认为这个查询可以做到这一点:

SELECT person, MIN(score) FROM golf_scores GROUP BY person ORDER BY score LIMIT 3;

但我收到以下错误:

ERROR 1055 (42000): Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'records.golf_scores.score' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

score 添加到 GROUP BY 列表只会返回最低的 3 个总分,而不管 person 列中的重复项。

如何在 MySQL 中获得所需的输出?

最佳答案

由于 order by 子句在 select 子句之后执行,请尝试为 min(score) 设置一个别名。

SELECT person, MIN(score) as min_score FROM golf_scores GROUP BY person ORDER BY min_score LIMIT 3;

关于mysql - 按类别显示 MySQL 8 中的前 N ​​个分数,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702226/

相关文章:

mysql - 无法从 Spring Boot Docker 容器连接到本地 MySQL 数据库服务器

php - 保持代码、数据库结构和数据库数据在修订之间同步

sql - 多个 GROUP BY 列合并为一列

php - 按字母顺序排列数组结果 PHP

mysql - 按人选择前 4 个分数,但至少需要两个位置

mysqldump 适用于较旧的 mysql 版本,从 mysql 8 到 mysql 5.7

MySQL 连接器在 DbProviderFactories.GetFactory 期间失败

mysql - 其中哪一个是有效的查询?

group-by - Mysql 加速 max() group by

MySQL 8 的 Ansible 安装 - 在没有 mysql-apt-config 的情况下安装存储库