2012-11-21 2 views
3

이 가정 번째 최고의 가치를 얻으려면? 예를 들어 어떻게 우리가 두 개의 테이블이

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

GameScores 테이블에 기본 키가 있습니까? 그건 뭐예요? –

+0

@LuisSiquot 네, session_id입니다. – Jofsey

+0

글쎄, 첫 번째 점수가 같은 두 개의 레코드가있는 경우 쿼리를 수행해야하는 대상 : A) 둘 다 삭제합니다. B) 둘 중 하나를 두 번째로 사용합니까 ??? –

답변

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 

당신이 할 수있는 이 쿼리에서 세션별로 그룹화하지 마십시오. 하위 쿼리에 넣고 여기에 session_id

+1

"MAX (Score as as Score)"를 앨리어싱하여 순환 참조 오류가 발생할 수 있습니다. 적어도 쿼리를 테스트 할 때 Access 2010에서 했었습니다. –

+0

언급하는 것이 좋습니다. 고마워요 – Marc

+0

@lescott 작동합니까? – Marc

0

얻을 gamescore에 가입해야하는 이유 그래서 내가 다른 접근 방식을했다

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; 
+0

'over' 및 관련 ms-access에 존재하지 않습니다. –

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 
0

오라클 SQL에 대한 코드는 내가 ...가요 이것이 다른 답보다 좋을지 모르겠지만이 방법으로 해결하고 싶습니다.

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)); 
관련 문제