2016-11-16 34 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