2

我正在尝试从学生表中获得前 5 分。表看起来像这样。

   table: student

   id name   score

   1    a     100
   2    b     100
   3    c     90
   4    d     87
   5    e     85
   6    f     88
   7    g     83
   9    h     92

如果我做

   select name,score from student order by score desc limit 5

   a    100
   b    100
   h     92
   c     90
   f     88

但是,我想看到这个结果

   a    100
   b    100
   h     92
   c     90
   f     88
   d     87

我试图找出重复的分数作为计数之一有任何解决方案吗?提前致谢。

4

4 回答 4

3
SELECT s.*
FROM student AS s
  JOIN
    ( SELECT DISTINCT score
      FROM student
      ORDER BY score DESC
          LIMIT 5
    ) AS lim
    ON s.score = lim.score 
ORDER BY s.score DESC ;
于 2013-02-20T16:35:43.243 回答
2

这是一种方法:

select s.*
from student s
where s.score >= (select score
                  from (select distinct score from student order by score desc limit 5) s
                  order by score
                  limit 1
                 )

这将在最内部的子查询中按降序获取分数。它将这限制为五个不同的分数。然后,它找到最小值,并返回所有具有此分数或更高分数的行。

于 2013-02-20T16:34:53.003 回答
1

尝试使用GROUP BY

SELECT 
    score
    COUNT(*) AS score_count
FROM 
    student 
GROUP BY
    score
ORDER BY
    score desc 
LIMIT 5
于 2013-02-20T16:23:39.813 回答
0

这是sql小提琴

  SELECT s.id, s.name,s.score FROM tbl_student AS s INNER JOIN (SELECT * FROM tbl_student ORDER BY score DESC LIMIT 0,5) AS s2 ON s2.id=s.id order by s.score desc
于 2013-02-21T19:17:35.170 回答