3

假设我们有两个表:

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
4

4 回答 4

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

于 2012-11-21T13:36:07.947 回答
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;
于 2012-11-21T13:43:08.740 回答
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
于 2012-11-21T13:53:01.593 回答
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));
于 2012-11-21T15:09:49.557 回答