2016-11-16 40 views
0

我有一組數據表示人們如何排列各種特徵。我試圖將數據透視兩列,但列數據包含在一列中,並且有一列作爲鑑別器。SQL數據透視列數據在具有鑑別器列的單列中

這是場景。人們被給予三種特徵的清單,並按照對它們的重要性排序。他們分別得到兩個三個特徵的列表,並要求從最重要到最不重要的每個列表1至3進行排名。

+----------+-------+----------------+---------------+------+ 
| RecordNo | Name | QuestionNumber | QuestionGroup | Rank | 
+----------+-------+----------------+---------------+------+ 
|  1 | Bob |  1  |  1  | 2 | 
|  2 | Bob |  2  |  1  | 1 | 
|  3 | Bob |  3  |  1  | 3 | 
|  4 | Bob |  1  |  2  | 1 | 
|  5 | Bob |  2  |  2  | 2 | 
|  6 | Bob |  3  |  2  | 3 | 
|  7 | Sally |  1  |  1  | 3 | 
|  8 | Sally |  2  |  1  | 2 | 
|  9 | Sally |  3  |  1  | 1 | 
| 10 | Sally |  1  |  2  | 1 | 
| 11 | Sally |  2  |  2  | 3 | 
| 12 | Sally |  3  |  2  | 2 | 
+----------+-------+----------------+---------------+------+ 

我想直到結束是數據的PIVOT所以它看起來像這樣..

+----------+-------+-----------+-----------+-----------+------------+------------+------------+ 
| RecordNo | Name | Question1 | Question2 | Question3 | Question 1 | Question 2 | Question 3 | 
|   |  | Group 1 | Group 1 | Group 1 | Group 2 | Group 2 | Group 2 | 
+----------+-------+-----------+-----------+-----------+------------+------------+------------+ 
|  1 | Bob |  2  |  1  |  3  |  1  |  2  |  3  | 
|  2 | Sally |  3  |  2  |  1  |  1  |  3  |  2  | 
+----------+-------+-----------+-----------+-----------+------------+------------+------------+ 

我知道該怎麼做一個樞軸上多列great article on it here但我不能當數據位於由鑑別器列(QuestionGroup)分隔的同一列(QuestionNumber)中時,該如何進行透視。

我還創建了一個在線表here

回答

2

我覺得擺動用最簡單的方法是有條件聚集:

select name, 
     max(case when questiongroup = 1 and questionnumber = 1 then rank end) as q_1_1, 
     max(case when questiongroup = 1 and questionnumber = 2 then rank end) as q_1_2, 
     max(case when questiongroup = 1 and questionnumber = 3 then rank end) as q_1_3, 
     max(case when questiongroup = 2 and questionnumber = 1 then rank end) as q_2_1, 
     max(case when questiongroup = 2 and questionnumber = 2 then rank end) as q_2_2, 
     max(case when questiongroup = 2 and questionnumber = 3 then rank end) as q_2_3 
from t 
group by name; 
+0

我覺得我有這麼的PIVOT關鍵字我忘記回到基本趕上了。 – webworm