基于ID列,我需要隔离数据。我有一张桌子,
ID Course Seats
1 CS 50
1 EC 60
1 ME 30
2 CS 60
2 EC 40
2 ME 25
2 EE 20
基本上,需要在下面的表单中设置结果,其中Seats列基于上表的ID。
Course Seats_ID = 1 Seats_ID = 2
CS 50 60
EC 60 40
ME 30 25
EE NULL 20
请告知如何完成它。
答案 0 :(得分:3)
MySQL没有 pivot 功能,这本质上就是你需要做的。为了旋转数据,您将使用带有CASE
表达式的聚合函数将数据从行转换为列:
select Course,
max(case when id=1 then seats end) Seats1,
max(case when id=2 then seats end) Seats2
from yourtable
group by course
这给出了结果:
| COURSE | SEATS1 | SEATS2 |
----------------------------
| CS | 50 | 60 |
| EC | 60 | 40 |
| EE | (null) | 20 |
| ME | 30 | 25 |
答案 1 :(得分:1)
您需要条件聚合:
select course,
sum(case when id = 1 then seats end) as Seats_1,
sum(case when id = 2 then seats end) as Seats_2
from t
group by course;