3现场SUMS,但仅在有价值时

时间:2012-01-27 18:54:31

标签: php mysql sum

这可能不是一件容易的事。我有桌子

游戏:

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没有任何价值 - 作为玩家数据库中每个玩家的总数......来自我耳朵的烟和蒸汽!!

1 个答案:

答案 0 :(得分: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语法而不是逗号样式的连接。