我有一个数据库,其中包含玩过的游戏及其得分。现在,我想运行一个查询,计算每个团队的总进球数超过x个(主场和客场总和)的所有结果。
数据库结构:
+----------+----------+---------------+---------------+
| HomeTeam | AwayTeam | HomeTeamGoals | AwayTeamGoals |
+----------+----------+---------------+---------------+
| team1 | team2 | 3 | 1 |
| team3 | team4 | 1 | 2 |
| team1 | team3 | 4 | 4 |
| team4 | team2 | 0 | 1 |
+----------+----------+---------------+---------------+
想要的结果:
+-------+----------+--------------------+
| team | played | games > 3.5 goals |
+-------+----------+--------------------+
| team1 | 2 | 2 |
| team2 | 2 | 1 |
| team3 | 2 | 1 |
| team4 | 2 | 0 |
+-------+----------+--------------------+
我正在看这样的东西:
SELECT *, COUNT(*) AS total FROM games WHERE homeTeamGoals + awayTeamGoals > 3.5 GROUP BY homeTeam
但这仅适用于主场比赛,因此我需要一种将客场比赛也添加到其中的方法。
答案 0 :(得分:1)
HomeTeam
和AwayTeam
的形式获得团队的结果。Group by
组成一个团队,以获取结果。尝试以下操作( SQL Fiddle DEMO ):
SELECT derived_t.team,
SUM(derived_t.played) AS played,
SUM(derived_t.games) AS 'games > 3.5 goals'
FROM
(
SELECT t1.HomeTeam as team,
COUNT(*) AS played,
SUM( IF(t1.HomeTeamGoals + t1.AwayTeamGoals > 3.5, 1, 0) ) AS games
FROM your_table AS t1
GROUP BY t1.HomeTeam
UNION ALL
SELECT t1.AwayTeam as team,
COUNT(*) AS played,
SUM( IF(t1.HomeTeamGoals + t1.AwayTeamGoals > 3.5, 1, 0) ) AS games
FROM your_table AS t1
GROUP BY t1.AwayTeam
) AS derived_t
GROUP BY derived_t.team