我有三张桌子:
players(playerID: integer, firstName: string, lastName: string)
gamestats(playerID: integer, gameID: integer, stat: string, result: double)
games(playerID: integer, gameID: integer, gametype: string)
吉文斯:
我想要的是返回以下内容:
SELECT SUM('hits')/SUM('throws') AS GameA_HitsPerThrow
WHERE games.gametype = 'gameA'
AND games.playerID = 1;
我知道这不是有效的SQL,但我希望psuedocode有意义。
非常感谢任何帮助。我是新来的。
修改
示例数据:
player(1, 'John', 'D')
player(2, 'Alice', 'H')
gamestats(1, 1708, hits, 4)
gamestats(1, 1708, throws, 4)
gamestats(2, 1708, hits, 8)
gamestats(2, 1708, throws, 7)
gamestats(1, 1709, hits, 9)
gamestats(1, 1709, throws, 13)
gamestats(2, 1709, hits, 6)
gamestats(2, 1709, throws, 10)
games(1, 1708, 'gameA')
games(2, 1708, 'gameA')
games(1, 1709, 'gameA')
games(2, 1709, 'gameA')
这是我到目前为止所做的,但它只是返回查询中的所有行(尽管由于某种原因它还包含重复项):
SELECT gamestats.stat, gamestats.result FROM `gamestats`
INNER JOIN games
ON gamestats.gameID = games.gameID
WHERE game.playerID = 1
AND games.gametype = 'gameA'
AND (gamestats.stat = 'hits' OR gamestats.stat = 'throws')
以下是它的回报:
(name, result):
(hits, 4)
(throws, 4)
(hits, 9)
(throws, 13)
这只是迈向目标的一小部分(非常小)。
答案 0 :(得分:2)
您没有提及表名可能是此原因问题
SELECT SUM('hits')/SUM('throws') AS GameA_HitsPerThrow From yourTable
WHERE games.gametype = 'gameA';
答案 1 :(得分:0)
SELECT g.gameID, g.playerID,
SUM(CASE WHEN stat = 'hits' THEN result END)/
SUM(CASE WHEN stat = 'throw' THEN result END) AS GameAHitsPerThrow
FROM games AS g
JOIN gamestats AS s ON g.gameID = s.gameID and g.playerID = s.playerID
WHERE g.gameType = 'gameA'
GROUP BY g.gameID, g.playerID
您有重复的行,因为您没有在JOIN条件中包含playerID
。我不确定为什么每个玩家在games
表中都有单独的行。