拥有一个包含多个记录的mysql表,这些记录属于许多不同的用户,如下所示:
1,50
1,75
1,40
1,20
2,85
2,60
2,20
我需要获得每个id的等级,但是在找到他们的分数总和之后;
如果每个玩家的总得分相同,则排名应该相同。这给了我每个玩家的总数:
select id,sum(score) as total from table_scores group by id order by total desc;
是否可以找到上面的总和并用它来在一个查询中对玩家进行排名?
答案 0 :(得分:2)
接受的答案中遗漏了一些东西。在平局之后,排名需要被提升。如果你有2个并列第3名,那就没有第4名了。
以下查询是对已接受的SQL的调整以解释此问题,并重置排名变量(查询中的@r)以匹配行值。您可以避免在CASE / WHEN中额外添加但是将@row初始化为1而不是0但是然后行值减1并且即使行号没有价值,我的OCD也不会让它站起来。
select
id, total,
CASE WHEN @l=total THEN @r ELSE @r:=@row + 1 END as rank,
@l:=total,
@row:=@row + 1
FROM (
select
id, sum(score) as total
from
table_scores
group by
id
order by
total desc
) totals, (SELECT @r:=0, @row:=0, @l:=NULL) rank;
答案 1 :(得分:1)
您可以使用变量对行进行排名:
select
id, total,
CASE WHEN @l=total THEN @r ELSE @r:=@r+1 END as rank,
@l:=total
FROM (
select
id, sum(score) as total
from
table_scores
group by
id
order by
total desc
) totals, (SELECT @r:=0, @l:=NULL) rank;
请查看它有效here。
答案 2 :(得分:-1)
我找到了另一种解决这个问题的方法......这个方法基于JOIN子句
SET @rank = 0;
SELECT t1.id, t1.score, t2.rank
FROM (SELECT id, SUM(score) as score
FROM table_scores GROUP BY id ORDER BY score Desc) AS t1
INNER JOIN
(SELECT x.score, @rank:=@rank + 1 as rank FROM
(SELECT DISTINCT(SUM(score)) AS score
FROM table_scores
GROUP BY id ORDER BY score DESC) AS x) AS t2
ON t1.score = t2.score
这是SQL小提琴:http://sqlfiddle.com/#!9/2dcfc/16
P.S。有趣的是,有一种方法可以解决问题...