我有以下查询,我试图获得职业生涯中球员的进球总数和投票总数。
SELECT
p.PlayerID,
SUM(s.votes) AS Votes,
SUM(p.Goals) AS TotalGoals
FROM
PlayerDetails p
LEFT JOIN PlayerVotes s ON
p.PlayerID = s.PlayerID AND p.Season = s.Season
WHERE
p.PlayerID = $PlayerID
PlayerDetails table
PlayerID | Season | Round | Goals |
PlayerVotes table
PlayerID | Season | Votes |
表中数据的主要区别是PlayerDetails表具有多个行中一个赛季的玩家数据-例如弗雷德·史密斯(Fred Smith)玩10场游戏,因此每个游戏都有一行,包括PlayerID,Season,Round和Goals得分。 PlayerVotes表的每个赛季每个球员都有一行,列出该赛季的总票数。例如,在2017年,弗雷德·史密斯(Fred Smith)获得了10票,因此将有一行数据显示PlayerID,Season和Votes。
查询返回的是球员在整个职业生涯中的进球总数,但票数之和几乎是正确的。
我尝试删除联接上的AND“ p.Season = s.Season”,但这会使目标加倍,并计票。
如果我在PlayerVotes表上运行此基本查询,则结果符合预期
SELECT PlayerID, SUM(Votes)
FROM PlayerVotes
WHERE PlayerID = $PlayerID
答案 0 :(得分:1)
您可以尝试这样的脚本:
SELECT p.PlayerID, SUM(p.Goals) AS Goals, pv.Votes FROM PlayerDetails AS p
LEFT JOIN (
SELECT SUM(ppv.Votes) AS Votes, ppv.PlayerID, ppv.Season FROM PlayerVotes AS ppv
GROUP BY ppv.PlayerID, ppv.Season
) AS pv ON pv.PlayerID = p.PlayerID AND pv.Season = p.Season
WHERE p.PlayerID = $PlayerID;