【问题标题】:Show top N scores in MySQL 8 without duplicates by category按类别显示 MySQL 8 中的前 N ​​个分数且不重复
【发布时间】:2019-07-09 04:16:00
【问题描述】:

我在 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):ORDER BY 子句的表达式 #1 不在 GROUP BY 子句中,并且包含在功能上不依赖于 GROUP BY 子句中的列的非聚合列“records.golf_scores.score”;这与 sql_mode=only_full_group_by 不兼容

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

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

【问题讨论】:

  • 避免在 cmets 中回答问题。

标签: mysql group-by mysql-8.0


【解决方案1】:

您可以尝试使用row_number()

    select * from
    (
         SELECT person, score,row_number() over(partition by person order by score) as rn
         FROM golf_scores 
    )A where rn=1
    ORDER BY score LIMIT 3

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您回答这个问题!不幸的是,我的 MWE 有点太简单了,因为在实际表中,我的行中还有其他列。你能看看我打开的这个separate question,看看你能不能帮忙?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多