MySQL SUM多列

时间:2011-10-14 22:46:20

标签: mysql sum

我有另外一个关于总和的问题。 我想总结一支棒球队的得分,加上在作为参赛者比赛时作为本地比赛得分的得分。

匹配表是这样的:

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

我想按团队分组,通过添加状态为“已播放”状态的比赛得分显示每个团队的总分

对于每支球队:当IdTeamHome时,SUM ScoreHome +当IdTeamAway时的SUM ScoreAway

我该怎么做?

感谢。

1 个答案:

答案 0 :(得分: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