如何使用MySQL中的聚合和UNION解决此问题?

时间:2011-09-19 04:48:28

标签: mysql group-by sql-order-by union

如果我的数据是

match homeTeam  awayTeam  homeTeamID  awayTeamID  homePoints awayPoints
  1    Alpha      Beta        1           2           4          2
  2    Gamma      Delta       3           4           6          0
  3    Alpha      Gamma       1           3           2          4
  4    Delta      Beta        4           2           3          3

我需要为他们制作一个梯子,但我不能正确地做到这一点

结果应如下所示

Name  played  Points
Gamma    2      10
Alpha    2       6
Beta     2       5
Delta    2       3

到目前为止,我的代码看起来像这样

$query = "SELECT *
    FROM (
        SELECT homeTeam AS teamName,
            COUNT(homeTeamID) AS matches_played,
            SUM(if(homeTeamID, homePoints, 0)) AS total_points
            FROM matches
        UNION ALL SELECT awayTeam AS teamName,
            COUNT(awayTeamID) AS matches_played,
            SUM(if(awayTeamID, awayPoints, 0)) AS total_points
            FROM matches
        ) all_points
    GROUP BY teamName
    ORDER BY total_points DESC  ";

但所有这一切都表明ALPHA打了4场比赛得到15分,BETA打了4场比赛得到9分--Gamma&三角洲走了:(

1 个答案:

答案 0 :(得分:4)

内部查询中没有GROUP BY子句。 但它仍然是不正确的。尝试:

SELECT teamName, COUNT(*) AS played, SUM(points) as points
    FROM (
        SELECT homeTeam AS teamName,
            homePoints AS points
            FROM matches
        UNION ALL SELECT awayTeam AS teamName,
            awayPoints AS points
            FROM matches
        ) all_points
    GROUP BY teamName
    ORDER BY total_points DESC