Mysql Max with Group by query

时间:2012-07-25 21:50:26

标签: mysql

我有一个可能是'经典'的mysql max / group 这是我的基本表格结构。

id | userid | username | date | score
1 | 1111 | joe | 2012-05-16 | 1000
2 | 2222 | john | 2012-03-17 | 2000
3 | 3333 | jill | 2012-02-11 | 3000
4 | 2222 | john | 2012-12-25 | 5000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000
7 | 1111 | joe | 2012-01-14 | 500
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000

我想得到每个用户的最高分。 每个用户应该只在结果中显示一个分数。

My desired result is
id | userid | username | date | score
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000

如果用户的最高分数出现多次(例如1& 6),则应显示最近的日期。

这是我当前的查询

select s.*
from scores as s
inner join (
    select userid, max(score) as max_score
    from scores
    group by userid
    ) t on s.userid = t.userid and s.score = t.max_score
order by score DESC, date DESC

返回

的错误结果
id | userid | username | date | score
8 | 2222 | john | 2012-06-29 | 6000
9 | 4444 | bill | 2012-08-08 | 4000
5 | 3333 | jill | 2012-04-08 | 4000
6 | 1111 | joe | 2012-06-17 | 1000
1 | 1111 | joe | 2012-05-16 | 1000

有关如何解决此问题的任何建议?

我还应该提到userid和username之间的关系不是一对一的。

1 个答案:

答案 0 :(得分:1)

这应该可以为您提供所需的结果。由于MySql没有PARTITION函数作为SQL SERVER,我使用了一个已知的工作。

SELECT tmp.id, tmp.userid,tmp.username,tmp.`date`,score FROM
   (SELECT *, IF(@prev<>userid, @rownum := 1, @rownum := @rownum+1 ) AS rank,
           @prev := userid
    FROM scores s0
    JOIN (SELECT @rownum := NULL, @prev := 0) AS r
    ORDER BY s0.userid, s0.score DESC, s0.`date` DESC
   ) AS tmp
WHERE tmp.rank=1
ORDER BY tmp.score DESC, tmp.`date` desc