在SQL中查找具有最大值的记录

时间:2012-01-04 00:02:56

标签: mysql sql max greatest-n-per-group

我有下表:

Class, Name, Score
1, Anna, 34
1, Andy, 80
2, Brooke, 90
2, Brad, 70
3, Charles, 67
3, Christina, 66

如何在每个“班级”中找到“最高分数”的“姓名”?

必需输出:

Class, Name, Score
1, Andy, 80
2, Brooke, 90
3, Charles, 67

这是针对MySQL的。

3 个答案:

答案 0 :(得分:4)

WITH ClassScores AS
(
    SELECT 1 AS class, 'Anna' AS name, 34 AS score 
    UNION
    SELECT 1, 'Andy', 80  
    UNION
    SELECT 2, 'Brooke', 90  
    UNION
    SELECT 2, 'Brad', 70  
    UNION
    SELECT 3, 'Charles', 67  
    UNION
    SELECT 3, 'Christina', 66 
)

SELECT C1.Class, C1.Name, C1.Score
  FROM ClassScores AS C1
  JOIN (SELECT Class, MAX(Score) AS MaxScore
          FROM ClassScores
         GROUP BY Class
       ) AS C2
    ON C1.Class = C2.Class
   AND C1.Score = C2.MaxScore
 ORDER BY C1.Class;

答案 1 :(得分:1)

另一种方式 - 如果ClassScores有(隐藏)PRIMARY KEY

SELECT 
    cs.Class
  , cs.Name
  , cs.Score
FROM 
      ( SELECT DISTINCT Class 
        FROM ClassScores 
      ) AS csd
  JOIN 
      ClassScores AS cs
    ON cs.PK = 
       ( SELECT csm.PK
         FROM ClassScores csm
         WHERE csm.Class = csd.Class
         ORDER BY csm.Score DESC
         LIMIT 1
       )

答案 2 :(得分:0)

使用UNION然后您可以单独使用三个select语句。它会很好地清理代码。

尝试..

select class, name, max(score) as "Score" from yourTable where class=1
UNION
select class, name, max(score) as "Score" from yourTable where class=2
UNION
select class,name,max(score) as "Score" from yourTable where class=3