2013-04-03 133 views
0

基於ID列,我需要分離數據。我有一個表,根據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 

基本上,需要結果在下面的形式,其中座椅列基於上表中的ID設定。

Course Seats_ID = 1 Seats_ID = 2 
CS  50    60 
EC  60    40 
ME  30    25 
EE  NULL   20 

請指教如何完成它。

回答

3

MySQL沒有樞軸函數,這基本上是你需要做的。爲了旋轉的數據,您將使用聚合函數與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 

SQL Fiddle with Demo

這給出結果:

| COURSE | SEATS1 | SEATS2 | 
---------------------------- 
|  CS |  50 |  60 | 
|  EC |  60 |  40 | 
|  EE | (null) |  20 | 
|  ME |  30 |  25 | 
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;