2011-10-14 65 views
3

我還有一個關於sum的問題。 我想總結一支棒球隊的得分情況,並在以訪問者身份參加比賽時以得分作爲本地球員的得分。MySQL SUM多列

的匹配表是這樣的:

Baseball_matches (Id, IdTeamHome, IdTeamAway, ScoreHome, ScoreAway, Status) 

我想通過團隊組,顯示出通過增加得分有狀態操作系統匹配的爲每個團隊的總比分「中扮演」

對於每個團隊:SUM ScoreHome IdTeamHome + SUM ScoreAway當IdTeamAway

我該怎麼做?

謝謝。

回答

2
SELECT Team, 
     SUM(Score) AS Score, 
     SUM(Won) AS Won, 
     SUM(Lost) AS Lost 
FROM (SELECT IdTeamHome  AS Team, 
       SUM(ScoreHome) AS Score, 
       SUM(CASE 
        WHEN ScoreHome > ScoreAway THEN 1 
        ELSE 0 
        END)  AS Won, 
     SUM(CASE 
       WHEN ScoreHome < ScoreAway THEN 1 
       ELSE 0 
      END)  AS Lost 
     FROM matches 
     WHERE Status = 'Played' 
     GROUP BY IdTeamHome 
     UNION ALL 
     SELECT IdTeamAway  AS Team, 
       SUM(ScoreAway) AS Score, 
       SUM(CASE 
        WHEN ScoreHome < ScoreAway THEN 1 
        ELSE 0 
        END)  AS Won, 
     SUM(CASE 
       WHEN ScoreHome > ScoreAway THEN 1 
       ELSE 0 
      END)  AS Lost 
     FROM matches 
     WHERE Status = 'Played' 
     GROUP BY IdTeamAway) D 
GROUP BY Team 
+0

謝謝馬丁,太棒了!另外,我想在同一查詢中檢索一個團隊贏得和輸掉的比賽數量......這可能嗎? –

+0

@MikeJohnson - 查看編輯。 –

+0

太棒了!它看起來非常複雜。它是否會爲一張大型比賽表正常工作?我非常擔心臨時表和所有這些東西。性能對於這個項目非常重要! –