CREATE TABLE `players` (
`pid` int(2) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`score` int(2) NOT NULL,
`game` varchar(20) NOT NULL,
PRIMARY KEY (`pid`),
UNIQUE KEY `pid` (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `players` (`pid`, `name`, `score`, `game`) VALUES
(1, 'Samual', 25, 'aa'),
(2, 'Vino', 20, 'aa'),
(3, 'John', 20, 'aa'),
(4, 'Samual', 22, 'bb'),
(5, 'Samual', 21, 'aa'),
(6, 'Vino', 24, 'aa'),
(7, 'John', 25, 'aa'),
(8, 'Vino', 26, 'cc'),
(9, 'John', 23, 'cc'),
(10, 'John', 19, 'aa'),
(11, 'Vino', 20, 'aa'),
(12, 'Samual', 20, 'aa');
在上表中,我希望此查询根据该玩家在比赛中玩的特定游戏所获得的分数总和,按降序获取玩家的排名。
SELECT pid, name, SUM(score) as score, game, rank
FROM (
SELECT pid, name, score, game,
@curRank := IF(@prevRank = score, @curRank, @incRank) AS rank,
@incRank := @incRank + 1,
@prevRank := score
FROM player p, (SELECT @curRank :=0, @prevRank := NULL, @incRank := 1) r
WHERE game='aa'
ORDER BY score DESC
) s WHERE name ='John'
但是查询没有以假定的格式输出结果,我希望查询总结特定游戏中的所有玩家得分并给出该玩家的等级并考虑领带情况
谢谢。答案 0 :(得分:1)
您需要在子查询中进行聚合,然后使用变量来获得排名:
select pid, name, game, score, (@rn := @rn + 1) as rank
from (select pid, name, game, SUM(score) as score
from player
where game = 'aa'
group by pid, game
) p cross join
(select @rn := 0) vars
order by score desc;
答案 1 :(得分:0)
您希望使用group by语句而不是subselect来解决此特定类型的问题。