2014-01-30 60 views
0

我正在寻找一种解决方案,以将以下列转换为t-SQL的两个新行(我使用2008年,如果重要)。TSQL - 行列与新列

这里是什么,我有一个例子:

[Question1] | [Question2] | [Question3] | [Question4] | [Question5] | [Question6] 
1 'Answer1'  'Answer2'  'Answer3'  'Answer4'  'Answer5'  'Answer6' 

这里是我想什么一个例子:

[Questions] | [Answers] 
1 'Question1' 'Answer1' 
2 'Question2' 'Answer2' 
3 'Question3' 'Answer3' 
4 'Question4' 'Answer4' 
5 'Question5' 'Answer5' 
6 'Question6' 'Answer6' 

我希望我的例子是很清晰。

谢谢。


因此,在用户2989408和M.Ali之间,我能够拼凑查询。 我主要使用user2989408的查询,但很快发现我需要为我的查询设置数据类型,否则它将无法工作。我只是施放(列为varchar(max)),它工作。

这是我最终的结果。

select 
    Question 
, Answer 
from 
    (select 
    , cast(Question1 as varchar(max)) 
    , cast(Question2 as varchar(max)) 
    , cast(Question3 as varchar(max)) 
    , cast(Question4 as varchar(max)) 
    , cast(Question5 as varchar(max)) 
    , cast(Question6 as varchar(max)) 
    from table) p 
unpivot 
    (Answers for Questions in 
     ( Question1 
     , Question2 
     , Question3 
     , Question4 
     , Question5 
     , Question6) 
)AS unpvt; 

非常感谢。

+2

尝试UNPIVOT。 http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx – PeterRing

回答

3

试试这个UNPIVOT查询。它应该工作。

SELECT ID, Questions, Answers 
FROM 
    (SELECT ID, Question1, Question2, Question3, Question4, Question5, Question6 
    FROM Table) p 
UNPIVOT 
    (Answers FOR Questions IN 
     (Question1, Question2, Question3, Question4, Question5, Question6) 
)AS unpvt; 
1
DECLARE @TABLE TABLE([Questions] NVARCHAR(100),[Answers] NVARCHAR(100)) 
INSERT INTO @TABLE VALUES 
('Question1','Answer1'),('Question2','Answer2'),('Question3','Answer3'), 
('Question4','Answer4'),('Question5','Answer5'),('Question6','Answer6') 

SELECT * FROM 
(
SELECT * FROM @TABLE) T 
PIVOT (MAX([Answers]) 
     FOR [Questions] 
     IN ([Question1],[Question2],[Question3] 
       ,[Question4],[Question5],[Question6]) 
     )p 


╔═══════════╦═══════════╦═══════════╦═══════════╦═══════════╦═══════════╗ 
║ Question1 ║ Question2 ║ Question3 ║ Question4 ║ Question5 ║ Question6 ║ 
╠═══════════╬═══════════╬═══════════╬═══════════╬═══════════╬═══════════╣ 
║ Answer1 ║ Answer2 ║ Answer3 ║ Answer4 ║ Answer5 ║ Answer6 ║ 
╚═══════════╩═══════════╩═══════════╩═══════════╩═══════════╩═══════════╝ 
+0

OP希望它成为其他方式。 – user2989408