5

我正在建立一个“前 3 名”排行榜。我想显示前三名的分数,绘制每人的最大值,但我不想限制 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 中执行此操作?

4

6 回答 6

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

小提琴

于 2013-06-01T08:52:19.603 回答
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
于 2013-06-01T08:56:21.153 回答
1

我会尝试类似的东西:

SELECT * FROM mytable
WHERE score IN (SELECT DISTINCT score FROM mytable ORDER BY score DESC LIMIT 3)
ORDER BY score DESC
于 2013-06-01T08:53:49.800 回答
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 ║
╚══════╩═══════╝
于 2013-06-01T08:47:30.367 回答
1

这将给出前三名的分数,无论平局如何。

score按分数从组中选择mytableORDER BY scoreDESC LIMIT 3

现在得到第三个分数。

SELECT MIN( score') FROM (SELECTscore FROMmytable group by score ORDER BYscore` DESC LIMIT 3) as top3

最终得到等于或高于第三分的一切

SELECT * FROM mytableWHERE score' >= (SELECT MIN(score') FROM (SELECT scoreFROM mtyablegroup by score' ORDER BYscore` DESC LIMIT 3) as top3)

于 2013-06-01T08:59:03.053 回答
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
于 2013-06-01T10:22:58.350 回答