[英]Joining tables and returning the correct aggregation
我正在使用Sean Lahman的“棒球”數據庫來匯總2010年至2015年之間各隊的奔跑,命中和“擊球”,獲勝情況。我想加入“隊”和“擊球”表,並使用teamID上的分組功能返回總金額在“團隊”表中按團隊查看奔跑,命中,擊球以及獲勝和失利。
例如,從“團隊”表中,我想逐年返回勝負
team ID Name Wins Losses Year
ARI Arizona Diamondbacks 65 97 2010
ARI Arizona Diamondbacks 94 68 2011
從打擊表中,這是我想要的輸出
year teamID Runs Hits At Bats
2012 ARI 734 1416 5462
2015 ARI 720 1494 5649
我嘗試了以下查詢,但它返回了獲勝和虧損列的膨脹值:
select b.yearID, b.teamID, SUM(b.R) as Runs, SUM(b.H) as Hits, SUM(b.AB) as At_Bats,
t.name as Team_Name, SUM(t.W) as Wins, SUM(t.L) as Losses
from Batting b, Teams t
where b.teamID = t.teamID and b.yearID=t.yearID and b.yearID between '2010' and '2015'
group by b.teamID, b.yearID, t.name, t.W, t.L
order by b.teamID
可以在此處找到數據庫的文檔http://www.seanlahman.com/files/database/readme2017.txt
盡管我在文檔中找不到該記錄,但是我猜想teamID和yearID的每個組合都唯一標識Teams表中的記錄。 在總結贏與輸時,您可以將它們乘以相關玩家的數量。 所以不要在tW和tL上求和:
select b.yearID, b.teamID, SUM(b.R) as Runs, SUM(b.H) as Hits, SUM(b.AB) as At_Bats,
t.name as Team_Name, t.W as Wins, t.L as Losses
from Batting b, Teams t
where b.teamID = t.teamID and b.yearID=t.yearID and b.yearID between '2010' and '2015'
group by b.teamID, b.yearID, t.name, t.W, t.L
order by b.teamID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.