SQL Group By:获取'max'记录的值

时间:2012-08-20 22:12:04

标签: mysql sql group-by

我有一个scores表:

id
user
score
date

现在,我可以通过

轻松选择前10名的高分
SELECT user, score, date FROM scores ORDER BY score DESC

但是,我想每个用户只包含一个分数,即最高分。我会从像

这样的东西开始
SELECT user, MAX(score) AS score FROM scores GROUP BY user ORDER BY score DESC

然而,现在我已经失去了记录得分最高的date。我怎么得到它?

4 个答案:

答案 0 :(得分:1)

你可以再次JOIN在桌子上:

SELECT s1.user, max(s1.dt), s2.mxscore as score
FROM scores s1
inner join 
(
    select user, max(score) mxscore
    from scores
    GROUP BY user 
) s2
    on s1.user = s2.user
    and s1.score = s2.mxscore
GROUP BY s1.username, s2.mxscore
ORDER BY score DESC

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

事实上,您根本不需要GROUP BY

以下是查询:

SELECT scores.id, scores.user, scores.score, scores.date
FROM scores
WHERE NOT EXISTS (
  SELECT * 
  FROM scores AS _scores
  WHERE _scores.user = scores.user
  AND (
    _scores.score > scores.score
    OR
    _scores.score = scores.score AND _scores.id < scores.id) 
)

SQL Fiddle看它是否有效。

请注意,此查询可以正确处理用户多次获得最高分数的情况(它返回第一个最高分数的记录)。

答案 2 :(得分:0)

您需要将结果与原始表格联系起来:

select a.user, a.maxScore, b.maxDate
from (
    select user, max(score) as maxScore 
    from scores group by user ) as a
inner join (
    select user, score, max(date) as maxDate 
    from scores group by user, score) as b on a.user = b.user and a.maxScore=b.score
order by
    a.maxScore desc

此查询将返回每个用户的最高分数,以及评分此最高分数的最后日期(冗余,但为真)

答案 3 :(得分:0)

SELECT   a.*
FROM     scores a
JOIN     (
         SELECT   MAX(a.id) AS id
         FROM     scores a
         JOIN     (
                  SELECT   user, MAX(score) AS score
                  FROM     scores
                  GROUP BY user
                  ) b ON a.user  = b.user
                     AND a.score = b.score
         GROUP BY a.user, 
                  a.score
         ) b ON a.id = b.id
ORDER BY a.score DESC

这将考虑每个用户拥有多个相同最高得分的情况。在这种情况下,它只需要最大id