我有一张带有游戏得分的表格(“得分”)。该表在游戏中有一个列Team1和一个列Team2(Team1的对手)以及他们的得分。这是一个示例:
------------------------------------------
| id | Team1 | Score1 | Team2 | Score2 |
------------------------------------------
| 1 | Reds | 1 | Blues | 6 |
| 2 | Blues | 5 | Greens | 2 |
| 3 | Greens | 3 | Whites | 4 |
| 4 | Whites | 0 | Greens | 7 |
------------------------------------------
我想要的是一张桌子(“ GameCounts”),其中列出了每个团队参加过多少场比赛,无论该团队是Team1还是Team2。这是我想要的示例:
-----------------------
| Team | GameCount |
-----------------------
| Reds | 1 |
| Blues | 2 |
| Greens | 3 |
| Whites | 2 |
-----------------------
解决了这一问题之后,我想编写另一个表格(“ ScoreSum”),列出每个球队的得分总和:
-----------------------
| Team | ScoreSum |
-----------------------
| Reds | 1 |
-----------------------
| Blues | 11 |
-----------------------
| Greens | 12 |
-----------------------
| Whites | 4 |
-----------------------
我尝试过的每个MySQL查询都没有完全关闭。谢谢!
答案 0 :(得分:2)
您可以通过制作派生的球队和得分表,然后对每个球队名称及其得分的出现进行汇总来在一个查询中完成所有操作:
SELECT Team, COUNT(*) AS GameCount, SUM(Score) AS ScoreSum
FROM (SELECT Team1 AS Team,
Score1 AS Score
FROM Scores
UNION ALL
SELECT Team2 AS Team,
Score2 AS Score
FROM Scores) S
GROUP BY Team
输出:
Team GameCount ScoreSum
Blues 2 11
Greens 3 12
Reds 1 1
Whites 2 4