简体   繁体   English

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

[英]SQL Group By: Get values of 'max' record

I have a scores table: 我有一个scores表:

id
user
score
date

Now, I can easily select a top 10 highscore with 现在,我可以轻松选择前10名的高分

SELECT user, score, date FROM scores ORDER BY score DESC

However, I'd like to include only one score per user, namely his highest. 但是,我想每个用户只包含一个分数,即他的最高分。 I would begin with something like 我会从类似的东西开始

SELECT user, MAX(score) AS score FROM scores GROUP BY user ORDER BY score DESC

However, now I've lost the date that highest score was recorded. 但是,现在我已经失去了记录最高分的date How do I get it? 我怎么得到它?

You can JOIN on the table again: 你可以再次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

See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo

In fact, you don't need a GROUP BY at all. 实际上,您根本不需要GROUP BY

Here's the query: 这是查询:

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) 
)

and SQL Fiddle to see it working. SQL小提琴看它工作。

Note that this query properly handles the case when a user had his max score several times (it returns the record for the first max score). 请注意,此查询可以正确处理用户多次获得最高分数的情况(它返回第一个最高分数的记录)。

You will need to relate your result with your original table: 您需要将结果与原始表格相关联:

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

This query will return the maximum score for each user, and the last date when this maximum score was scored (redundant, but true) 此查询将返回每个用户的最高分数,以及评分此最高分数的最后日期(冗余,但为真)

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

This will account for cases where you have more than one of the same highest score per user. 这将考虑到每个用户拥有多个相同最高得分的情况。 In that case, it will just take the maximum id . 在这种情况下,它只需要最大id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM