左连接以查找不同表中两列的总和

z4iuyo4d  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(336)

我有下面的问题,我试图得到一个球员在职业生涯中的总进球数和总票数。

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场比赛,因此每场比赛都有一行数据,包括球员ID、赛季、回合和得分。playervotes表中每个球员每个赛季都有一行该赛季的总票数。例如,在2017年,弗雷德·史密斯获得了10张选票,因此将有一行数据playerid、season和vots。
查询返回的是球员职业生涯中的进球总数,但投票总数几乎不正确。
我试过删除join上的and“p.season=s.season”,但这会使目标和票数增加一倍。
如果我在playervotes表上运行这个基本查询,结果与预期一样

SELECT PlayerID, SUM(Votes) 
FROM PlayerVotes 
WHERE PlayerID = $PlayerID
41zrol4v

41zrol4v1#

您可以尝试这样的脚本:

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;

相关问题