2012-01-27 60 views
0

這可能是一個沒有道理的。我有表3現場SUMS,但只有當有價值

遊戲:

guid(PK), puid, gScoreA, gTimesPlayed, gScoreB. 

球員:

puid(PK), pFname, pLname 

我想:

Select 
    player.puid, 
    (SUM(game.gScoreA)/SUM(game.gTimesPlayed)) as skillA, 
    (SUM(game.gScoreB)/SUM(game.gTimesPlayed)) as skillB 
FROM 
    player, 
    game 
WHERE 
    player.puid = game.puid 
ORDER BY 
    skillA DESC, 
    skillB DESC 

所以每場比賽的球員可以有兩種gScoreAgScoreB始終一個gTimesPlayed。所以,我想所有的SUM(game.gScoreA)SUM(game.gTimesPlayed)其中game.gScoreA具有價值和game.gScoreB不和SUM(game.gScoreB)/SUM(game.gTimesPlayed) WHERE gScoreA沒有價值,反之亦然分 - 作爲一個整體在從我的耳朵玩家數據庫...煙霧和蒸汽每個玩家!

+0

我認爲你的查詢應該給你想要的結果集,但是你必須在ORDER BY之前添加一個「GROUP BY player.puid」 – Abhay 2012-01-27 19:12:02

回答

2
SELECT 
    player.puid, 
    SUM(game.gScoreA)/SUM(IF(game.gScoreA IS NOT NULL, game.gTimesPlayed, 0)) as skillA, 
    SUM(game.gScoreB)/SUM(IF(game.gScoreB IS NOT NULL, game.gTimesPlayed, 0)) as skillB 
FROM player INNER JOIN game ON player.puid = game.puid 
GROUP BY player.puid 
ORDER BY 
    skillA DESC, 
    skillB DESC 

使用GROUP BY可以得到每個玩家的結果。

此外,使用JOIN語法而不是逗號式聯接。