mysql - 显示重复记录的最高 3 分

标签 mysql

我的 table 是

enter image description here

我想在页面上显示每个部分的最高 3 分,但是如果有人在前 3 分中有相似的分,我想根据分降序显示重复的分。我正在使用以下代码。

SELECT Name, Marks FROM mytable AS t1 
INNER JOIN (SELECT DISTINCT(Marks) AS best_marks FROM mytable ORDER BY Marks DESC LIMIT 3) AS t2 ON t1.Marks = t2.best_marks ORDER BY Marks DESC, Name ASC;

所以我的最终输出看起来,

enter image description here

请帮助我...我正在努力寻找解决方案。

最佳答案

这是使用 group_concat()substring_index() 获得前三名的技巧。这个想法是获得列表中的前三名。然后使用 find_in_set() 匹配到该列表:

select name, marks
from mytable t1 join
     (select section, substring_index(group_concat(distinct Marks order by Marks desc), ',', 3) as Marks3
      from mytable
      group by section
     ) tsum
     on t1.section = tsum.section and
        find_in_set(t1.Marks, tsum.Marks3) > 0
ORDER BY Marks DESC, Name ASC;

Here是一个 SQLFiddle,说明代码在语法上是正确的。

关于mysql - 显示重复记录的最高 3 分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848080/

相关文章:

php - 自动提示显示空白 li

php - 在查询中输入数字

mysql - 使用 SQL 查询的数据复制解决方案

php - 需要帮助为 select 语句编写 SQL 查询

mysql - 我将如何在 SQL/SQLALCHEMY 中设计相互依赖的外键

php - 如何在 Laravel 中使用 Eloquent 为相同的两个表创建不同的多对多关系

php - 在 codeigniter 中更新多个 id

MYSQL 日期范围 RFC 2822

MySQL : Select count group by day with custom starting and ending hours for a day

mysql - 基于多个计算值的 MySQL View