0

所以这是我的数据表的样子:

TeamNum Round   Points1   Points2
1       1       5         21
2       1       10        20
3       1       9         29
1       2       6         22
2       2       11        21
3       2       10        30
1       3       80        50

我还有第二张桌子:

TeamNum TeamName
1       goteam1
2       goteam2
3       goteam4-1

我希望 SQL 把它变成这样:

Team    Round1                      Round2            Round3            TeamName
1       (points1+points2 of round1) (same but for r2) (same but for r3) goteam1
2       (points1+points2 of round1) (same but for r2) (same but for r3) goteam2
3       (points1+points2 of round1) (same but for r2) (same but for r3) goteam4-1

上表的示例输出将是:

Team    Round1   Round2    Round3    TeamName
1       26       28        130       goteam1
2       30       32        0         goteam2
3       38       40        0         goteam4-1

实际数据有一堆“points1”和“points2”列,但只有3轮。

我对 SQL 很陌生,这就是我现在所拥有的:

select 
  `data`.`round`,
  `data`.`teamNumber`,
  sum(`Points1`) + sum(`Points2`) as score
from `data` join `teams` ON `teams`.`teamNumber` = `data`.`teamNumber`
group by `data`.`teamNumber` , `round`
order by `data`.`teamNumber`, `data`.`round`

但它根本不返回任何东西。如果我删除 join 语句,它会显示我想要的所有内容,但不会将 Round1、2 和 3 合并为列,它们都是单独的行。你们能帮帮我吗?谢谢!

4

3 回答 3

1

无需汇总:

SELECT
    t.teamnumber,
    COALESCE(r1.points1 + r1.points2, 0) AS round1,
    COALESCE(r2.points1 + r2.points2, 0) AS round2,
    COALESCE(r3.points1 + r3.points2, 0) AS round3,
    t.teamname
FROM teams t
LEFT JOIN data r1 ON r1.teamnumber = t.teamnumber AND r1.round = 1
LEFT JOIN data r2 ON r2.teamnumber = t.teamnumber AND r2.round = 2
LEFT JOIN data r3 ON r3.teamnumber = t.teamnumber AND r3.round = 3
于 2013-11-07T22:27:07.223 回答
1

使用条件聚合

SELECT t.teamnumber, t.teamname,
       SUM(CASE WHEN d.round = 1 THEN d.points1 + d.points2 ELSE 0 END) round1,
       SUM(CASE WHEN d.round = 2 THEN d.points1 + d.points2 ELSE 0 END) round2,
       SUM(CASE WHEN d.round = 3 THEN d.points1 + d.points2 ELSE 0 END) round3
  FROM data d JOIN teams t
    ON d.teamnumber = t.teamnumber
 GROUP BY t.teamnumber, t.teamname

输出:

| 团队编号 | 队名 | 第一轮 | 第2轮 | 第三轮 |
|------------|-----------|--------|--------|------ --|
| 1 | goteam1 | 26 | 28 | 130 |
| 2 | goteam2 | 30 | 32 | 0 |
| 3 | goteam4-1 | 38 | 40 | 0 |

这是SQLFiddle演示

于 2013-11-07T22:24:36.777 回答
0

像这样的东西:

 select teams.teamNumber,
  SUM(CASE WHEN Round=1 THEN `Points1`+`Points2`  ELSE 0 END)as Round1,
  SUM(CASE WHEN Round=2 THEN `Points1`+`Points2`  ELSE 0 END)as Round2,
  SUM(CASE WHEN Round=3 THEN `Points1`+`Points2`  ELSE 0 END)as Round3,
  teams.teamName
from `data` join `teams` ON `teams`.`teamNumber` = `data`.`teamNumber`
group by teamnumber , teamname
order by `data`.`teamNumber`, `data`.`round`
于 2013-11-07T22:23:19.937 回答