2015-10-06 39 views
0

我有一個表,看起來像這樣:SQL作爲列標題保持各行SELECT DISTINCT行值值

QuestionNum AnswerChoice 
    1   a 
    1   a 
    2   b 
    2   b 
    2   a 
    3   c 
    3   d 
    3   c 
    4   a 
    4   b 

我想選擇從QuestionNum列中的不同值的列標題仍然列出每個回答下面的選擇,所以它應該是這樣的:

1 2 3 4 
    a b c a 
    a b d b 
     a c 

我開始尋找透視表,但QuestionNum將是未知的。此外,我無法找出一種方法來從原始選擇多行。

+3

你怎麼知道哪些行應該在哪些行上?是否有一些問卷ID將他們聯繫在一起?如果沒有,你可以創建一個。這就是你要在 – Leslie

+0

上重要的是的,我忽略了那一欄。從技術上講,這些都與examInstanceID相關聯。每個考試都有X個問題,但我認爲我不能透過examInstanceID,因爲每個考試的問題可能會有所不同,因爲它們是從數據庫中隨機抽取的。 examInstanceId 1可能有問題1,2,3,4但examInstanceId 2可能有問題2,3,4,5。 – jpsnow72

+1

您可以動態生成將成爲列的問題列表http://stackoverflow.com/questions/ 14797691/dynamic-pivot-columns-in-sql-server – Leslie

回答

0

你可以用條件聚合來做到這一點。挑戰是你需要一把鑰匙,而row_number()提供了鑰匙:

select max(case when QuestionNum = 1 then AnswerChoice end) as q_1, 
     max(case when QuestionNum = 2 then AnswerChoice end) as q_2, 
     max(case when QuestionNum = 3 then AnswerChoice end) as q_3, 
     max(case when QuestionNum = 4 then AnswerChoice end) as q_4  
from (select t.*, 
      row_number() over (partition by QuestionNum order by examInstanceID) as seqnum 
     from table t 
    ) t 
group by seqnum;