2012-06-06 51 views
1

我正在爲測驗碗創建一個MySQL數據庫。該設計是爲了有一個包含所有的遊戲結果的橫表,具有交叉表的形式:如何統計團隊成員是MySQL交叉表中游戲中最高得分者的次數?

CREATE TABLE game_results(
    id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    game_id MEDIUMINT NOT NULL, 
    team_id SMALLINT NOT NULL, 
    score MEDIUMINT); 

我的問題是如何一數(即次的數量勝的隊伍,擁有數團隊是特定遊戲中得分最高的球隊)使用MySQL從表game_results

回答

2
SELECT COUNT(1) AS wins FROM game_results AS gr1 
LEFT JOIN game_results AS gr2 ON gr1.game_id=gr2.game_id AND gr2.team_id != 1234 
WHERE gr1.team_id = 1234 AND gr1.score > gr2.score 
1
SELECT old.team_id, 
     COUNT(old.team_id) AS Wins, 
     old.game_id 
FROM game_results AS old, 
    (SELECT MAX(score) AS score, 
      game_id 
    FROM game_results 
    GROUP BY game_id) AS nt 
WHERE old.score = nt.score 
    AND old.game_id = nt.game_id 
GROUP BY old.team_id 

編輯:忽略繪製遊戲

SELECT old.team_id, 
     COUNT(old.team_id) AS Wins, 
     old.game_id 
FROM game_results AS old, 
    (SELECT MAX(score) AS score, 
      game_id 
    FROM game_results 
    GROUP BY game_id) AS nt 
WHERE old.score = nt.score 
    AND old.game_id = nt.game_id 
    AND old.game_id NOT IN 
    (SELECT DISTINCT a.game_id 
    FROM game_results AS a, 
      game_results AS b 
    WHERE a.game_id = b.game_id 
     AND a.score = b.score 
     AND a.id != b.id) 
GROUP BY old.team_id