如何在SQL Server 2008R2中将多列转换为行

时间:2014-04-23 13:17:03

标签: tsql sql-server-2008-r2

我一直在尝试生成如上表所示的数据集。 任何建议都会非常有帮助。谢谢 enter image description here

2 个答案:

答案 0 :(得分:1)

/*
Set up temp table to work off
*/

create table #temp 
(a decimal(10,2), 
b decimal(10,2), 
c decimal(10,2), 
d decimal(10,2), 
e decimal(10,2), 
f decimal(10,2), 
dollor decimal(10,2),
YrQtr nvarchar(7))

insert #temp values
(105,5,8,51,40,15,29039.56,'2012-Q4'),
(109,5,5,49,40,14,16116.72,'2013-Q1'),
(109,4,4,55,41,22,21988.31,'2013-Q2'),
(105,3,4,52,36,21,14971.17,'2013-Q3'),
(93,3,2,47,35,18,25862.77,'2013-Q4')

*/



select 
    [Measure],[2012-Q4], [2013-Q1],  [2013-Q2], [2013-Q3], [2013-Q4] 
from(
    select A, B, C,  D, E, F, Dollor [zDollar],YrQtr
    from #temp)    as Source 
    UNPIVOT (
       vals   
       for [Measure] in([A],[B],[C],[D],[E],[F],[zDollar])
)as [unpivoted] 
pivot (
max(vals) 
for YrQtr in ([2012-Q4], [2013-Q1],  [2013-Q2], [2013-Q3], [2013-Q4]) 
) as t

需要注意的一点是,此脚本会按字母顺序排列生成的度量值 - 因此它将是A,B,C,D,Dollor,E,F而不是可能需要的A,B,C,D,E,F,Dollor。为了使它现在更简单,我只是将Dollar列别名以强制它到列表的末尾。

答案 1 :(得分:0)

汤姆,谢谢你, 我回到下面的查询

DECLARE  @TEMPQUES TABLE(MaxRange NVARCHAR(MAX),MinRange NVARCHAR(MAX),ReferenceTypeName NVARCHAR(MAX),Instructions NVARCHAR(MAX),Question NVARCHAR(MAX))
insert into @TEMPQUES
SELECT CAST(MaxRange AS nVARCHAR(100)),CAST(MinRange AS NVARCHAR(100)),QuestionnaireReferenceTypeName,Instructions,Question FROM vw_QuestionnaireAnswers WITH(NOLOCK) WHERE QuestionnaireID = 100000

SELECT [QA],[Dimenssion],[Is Material in good packing],[NCR],[Special remarks],[Length] FROM
(SELECT ISNULL(MaxRange,0)  AS MaxRange,ISNULL(MinRange,0) AS MinRange,
        ISNULL(ReferenceTypeName,'NA') AS ReferenceTypeName
        ,ISNULL(Instructions,'NA') AS Instructions,Question 
FROM @TEMPQUES ) AS Questionnaire
UNPIVOT( VALUE FOR [QA] IN([MaxRange],[MinRange],[ReferenceTypeName],[Instructions])
) AS [UNPIVOTED]
PIVOT(MAX(VALUE) FOR Question  IN  ([Dimenssion],[Is Material in good packing],[NCR],[Special remarks],[Length] ) )  AS PVTTable