0

我有一个看起来像这样的表:

+------+----------+----------+--------+
|  id  |  team    |   match  |  score |
+------+----------+----------+--------+
|  1   |     1    |    1     |  10    |
|  2   |     2    |    1     |  5     |
|  3   |     1    |    1     |  5     |
|  4   |     1    |    2     |   6    |
|  5   |     2    |    1     |   4    |
+------+----------+----------+--------+

我需要计算SUM()每场比赛和球队的所有分数,我知道如何计算总和......

SELECT SUM(score) AS team_a_score WHERE `match`='1'

我期待这样的事情......

+----------------+
| team_a_score   |
+----------------+
|    24          |
+----------------+

但我真正需要做的是分别获得第 1 队和第 2 队的分数,所以它会更像这样......

+----------------+----------------+
| team_a_score   |  team_b_score  |
+----------------+----------------+
|    15          |     9          |
+----------------+----------------+

希望这足够清楚

4

4 回答 4

6

看起来您希望结果在同一行中,因此您将使用以下命令:

select sum(case when team = 1 then score end) team_a,
  sum(case when team = 2 then score end) team_b
from yourtable
where `match` = 1

SQL Fiddle with Demo

于 2012-09-19T01:30:51.713 回答
1

这个怎么样

 SELECT team, SUM(score) AS team_a_score FROM some_table GROUP BY team

结果不会在列中(如您的问题中所述),而是在行中,每行都带有团队编号和总分

+----------+---------------+
|  team    |   score       |
+----------+---------------+
|     1    |    15         |
|     2    |     9         |
于 2012-09-19T01:27:45.053 回答
-1

使用GROUP_BY

SELECT SUM(score) AS team_a_score WHERE `match`='1' GROUP_BY team
于 2012-09-19T01:26:49.383 回答
-1
SELECT team,sum(score) AS team_score
FROM table_missed
WHERE `match`='1'
GROUP by team
于 2012-09-19T01:30:16.580 回答