TSQL - 具有新列的行的列

时间:2014-01-30 16:25:58

标签: sql sql-server sql-server-2008 tsql

我正在寻找一个slution来将以下列转换为带有t-SQL的两个新行(如果重要的话,我正在使用2008)。

以下是我所拥有的一个例子:

   [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'

我希望我的榜样足够清楚。

谢谢。


因此,在user2989408和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 个答案:

答案 0 :(得分: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 :(得分: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   ║
╚═══════════╩═══════════╩═══════════╩═══════════╩═══════════╩═══════════╝