前三名 - MySQL

时间:2013-06-01 08:45:32

标签: mysql

我正在建立一个“前3名得分”排行榜。我想显示前三个分数,每人最多,但我不想限制3,因为我想要显示前三名得分的人。例如,使用下面的数据,

+----+-----+
|Name|Score|
+----+-----+
|Matt|   17|
|Mark|   29|
|Luke|   28|
|John|   29|
|Paul|   27|
|Matt|   29|
|Mark|   22|
+----+-----+

我想要显示:

+------+-----+
|Name  |Score|
+------+-----+
|1.Matt|   30|
|2.Mark|   29|
|2.John|   29|
|3.Luke|   28|
+------+-----+

我的第一个想法是为每个人提取最大值,然后在分数改变后停止显示(使用PHP)。

select name, max(score)
from SCORES
group by name
order by name

有没有办法直接在SQL中执行此操作?

6 个答案:

答案 0 :(得分:6)

SELECT name, score
FROM SCORES
JOIN (SELECT distinct score score3
      FROM scores
      ORDER BY score DESC
      LIMIT 2, 1) x
ON score >= score3
ORDER by score DESC

FIDDLE

答案 1 :(得分:2)

SELECT name,score
    FROM SCORES
    WHERE score in (
        SELECT distinct s.score
        FROM SCORES as s
        ORDER BY s.score desc
        LIMIT 3)
    )
    ORDER BY score

答案 2 :(得分:1)

SELECT  Name, MAX(Score) Score
FROM    TableName a
WHERE   EXISTS
        (
            SELECT  1
            FROM    TableName b
            WHERE   a.Score = b.Score
            GROUP   BY Score
            ORDER   BY Score DESC
            LIMIT   3
        )
GROUP   BY Name
ORDER   BY Score DESC

根据上面给出的记录输出

╔══════╦═══════╗
║ NAME ║ SCORE ║
╠══════╬═══════╣
║ Mark ║    29 ║
║ John ║    29 ║
║ Matt ║    29 ║
║ Luke ║    28 ║
║ Paul ║    27 ║
╚══════╩═══════╝

答案 3 :(得分:1)

我会尝试类似的事情:

SELECT * FROM mytable
WHERE score IN (SELECT DISTINCT score FROM mytable ORDER BY score DESC LIMIT 3)
ORDER BY score DESC

答案 4 :(得分:1)

这将得出前三名,无论关系如何。

按分数选择score FROM mytable组 ORDER BY score DESC 限制3

现在获得第三个分数。

SELECT MIN(score') FROM (SELECT得分FROM mytable group by score ORDER BY得分`DESC 限制3)作为top3

最终让一切都等于或高于第三个分数

SELECT * FROM mytable WHERE score' >= (SELECT MIN(得分')FROM (按score得分'DESC选择mtyable FROM score' ORDER BY组 限制3)作为top3)

答案 5 :(得分:1)

这里是SQL FIDDLE

SELECT
  NAME,
  score
FROM SCORES
WHERE FIND_IN_SET(score,(SELECT
                           SUBSTRING_INDEX(GROUP_CONCAT( DISTINCT score ORDER BY score DESC),',',3)
                         FROM SCORES)) > 0
ORDER BY score desc