2012-12-20 174 views
1

我的問題:我有我的基表存儲用戶名和他們的反饋響應。在每個用戶的表格中,我有2個問題和2個回答。將列轉換爲SQL Server中的行

ans1 ans2是文本列,用戶可以在其中輸入他們對每個問題/答案對的評論。

輸入表:

username question1 question2 opt1 ans1 opt2 ans2 
----------------------------------------------------------------------- 
user1 ques1 ques2 a answer1 b answer2 
user2 ques1 ques2 c answer11 d answer21 

我想我的輸出(給定的輸入如上表)查詢應在以下格式產生結果:

Username Question Option Comment 
---------------------------------------------------- 
user1 ques1 a answer1 
user1 ques2 b answer2 
user2 ques1 c answer11 
user2 ques2 d answer21 

我嘗試這樣的查詢來獲得結果,但它是以某種方式採取所有可能的組合..請建議..

SELECT Username,Question,Answers,Options 
FROM 
(SELECT username,opt1,opt2,ans1,ans2,ques1,ques2 
FROM dbo.tab1) p 
    UNPIVOT(Question FOR q1 IN (ques1, ques2))AS unpvt1 
    UNPIVOT(Answers FOR answer1 IN (ans1, ans2))AS unpvt2 
    UNPIVOT(Options FOR a IN (opt1, opt2))AS unpvt3 
GO 

回答

0

我認爲你可以不使用UNPIVOT查詢;請檢查

select 
    distinct UserName, 
    Question1 AS Question, 
    Opt1 AS OPT, 
    Ans1 AS Comment 
From 
    tblFeedback where Question1='Quest1' 
UNION ALL 
select 
    distinct UserName, 
    Question2 AS Question, 
    Opt2 AS OPT, 
    Ans2 AS Comment 
From 
    tblFeedback where Question2='Quest2' 
+0

是的..這工作完美..謝謝你.. –