3

2 つのテーブルがあるとします。

Players(player_id int)
GameScores(player_id int, session_id int, score int)

すべてのプレーヤーの 2 番目に高いスコアのセッションをクエリするにはどうすればよいでしょうか?

たとえば、

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

これは、各プレーヤーの 2 番目に高いスコアを選択するクエリです。

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
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

これは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
  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 に答える