假设我们有两个表:
Players(player_id int)
GameScores(player_id int, session_id int, score int)
我们如何查询每位玩家的第二高得分会话?
例如,如果
Players
1
2
GameScores
(player_id, session_id, score)
1 1 10
1 2 20
1 3 40
2 4 10
2 5 20
Then result would be
(player_id, session_id)
1, 2
2, 4
答案 0 :(得分:4)
你能试试吗
SELECT GameScores.player_id, GameScores.session_id
FROM (
SELECT player_id,MAX(score) as SecondScore
FROM GameScores g
WHERE score < (SELECT Max(Score) FROM gameScore where gameScore.player_id = g.player_id)
GROUP BY player_id
) x
INNER JOIN GameScores ON x.player_id = gamescore.player_id
AND x.SecondScore = gamescore.score
这是为每个玩家选择第二个高分的查询
SELECT player_id,MAX(score) as SecondScore
FROM GameScores g
WHERE score < (SELECT Max(Score) FROM gameScore where gameScore.player_id = g.player_id)
GROUP BY player_id
您无法在此查询中按会话分组。这就是为什么你需要将它放在子查询中并将其加入gamescore
以获得session_id
答案 1 :(得分:0)
以下是Oracle sql的代码片段
select tbl.player_id,tbl.session_id from
(select p.player_id,g.session_id,g.score,rank() over (partition by p.player_id order by score desc) rnk from players p,
gamescores g
where p.player_id = g.player_id) tbl
where tbl.rnk = 2;
答案 2 :(得分:0)
select player_id, first(session_id) as session_id
from
GameScores inner join (
select player_id, max(score) as secondscore
from
GameScores left join (
select player_id, max(score) as firstscore
from GameScores
group by player_id
) as NotThisOnes on GameScores.player_id = NotThisOnes.player_id
and GameScores.score = NotThisOnes.firstscore
where NotThisOnes.player_id is null
group by player_id
) as thisare on GameScores.player_id = thisare.player_id
and GameScores.score = thisare.secondscore
group by player_id
答案 3 :(得分:0)
我采取了不同的方法......我不确定这是否比其他答案更好,但我想以这种方式解决:
SELECT
GameScores.player_id,
GameScores.session_id,
GameScores.score
FROM
GameScores
WHERE
GameScores.score=
(select max(score) from GameScores GameScores_2
where GameScores.player_id = GameScores_2.Player_ID
and GameScores_2.Score<
(select max(score) from GameScores GameScores_1
where GameScores_1.player_id = GameScores.player_id));