SQL整合数据并将其转换为列

时间:2013-11-07 22:16:47

标签: mysql sql database

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

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合并为列,它们是每个单独的行。你能帮助我吗?谢谢!

3 个答案:

答案 0 :(得分: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

输出:

| TEAMNUMBER |  TEAMNAME | ROUND1 | ROUND2 | ROUND3 |
|------------|-----------|--------|--------|--------|
|          1 |   goteam1 |     26 |     28 |    130 |
|          2 |   goteam2 |     30 |     32 |      0 |
|          3 | goteam4-1 |     38 |     40 |      0 |

这是 SQLFiddle 演示

答案 1 :(得分: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

答案 2 :(得分: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`