在SQL Server中将列转换为行

时间:2012-12-20 10:00:12

标签: sql sql-server

我的问题:我的基表存储了用户名及其反馈响应。在每个用户的表格中,我有2个问题和2个回复。

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

1 个答案:

答案 0 :(得分: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'