我有一张称为“玩家”的表格,其中包含蒂姆,鲍勃和乔恩玩过的3场比赛的得分。
playid | name | score
1 | Tim | 10
1 | Bob | 5
2 | Tim | 5
2 | Bob | 10
3 | Tim | 5
3 | Bob | 10
3 | Jon | 4
我希望能够计算出Tim,Bob和Jon获得第二名的次数,即Tim = 2,Bob = 1,Jon = 0。
我有以下查询:
SELECT name FROM players WHERE playid = 1 ORDER BY score Desc LIMIT 1, 1
哪个人的名字在第一场比赛中名列第二,即鲍勃,但我不知道如何将其扩展到所有游戏和玩家。最终,我还希望能够计算出它们获得第三,第四等的次数。
预先感谢
答案 0 :(得分:0)
尝试以下一项:
SELECT count(playid), name, score
FROM `players`
WHERE score = (SELECT MAX(score) FROM players WHERE score < (SELECT MAX(score) FROM players))
GROUP BY score, name;
答案 1 :(得分:0)
答案 2 :(得分:0)
具有多个联接和分组:
select pl.name, ifnull(counter, 0) counter from (
select distinct name from players) pl
left join (
select players.name, count(*) counter from players
inner join (
select p.playid, max(p.score) as secondscore from (
select players.* from players
left join (
select playid, max(score) as maxscore
from players
group by playid) p
on p.playid = players.playid and p.maxscore = players.score
where p.maxscore is null) p
group by p.playid
) p
on p.playid = players.playid and p.secondscore = players.score
group by players.name) p
on p.name = pl.name
请参见demo
答案 3 :(得分:0)
根据Raymond Nijland的评论,在MySQL 8.0+中,您可以使用窗口函数来实现此目的:
SELECT name, COUNT(*) AS second_place_count
FROM (
SELECT
name,
playid,
ROW_NUMBER() OVER (PARTITION BY playid ORDER BY score DESC) AS rn
FROM players
) AS ranks
WHERE ranks.rn = 2
GROUP BY name
...或者如果要将其扩展到所有位置:
SELECT
name,
rn AS place,
COUNT(*) AS place_count
FROM (
SELECT
name,
playid,
ROW_NUMBER() OVER (PARTITION BY playid ORDER BY score DESC) AS rn
FROM players
) AS ranks
GROUP BY
name,
rn