TSQL - Unpivot多列

时间:2013-05-13 13:15:41

标签: sql-server tsql pivot crosstab unpivot

如何在“one”中展开多列?

现在我对每一列都有一个univot,但这会产生很多空行。

请看截图。 enter image description here

在顶部,您可以看到输入数据。目前,我正在中间的桌子上写下这段代码:

SELECT [ID], [RowNumber],  [Year], [Sales]  FROM (
        SELECT ID, RowNumber, [Sales 2013] as [2013], [Sales 2014] as [2014]
        FROM mytable) p     UNPIVOT (
        [Sales] FOR [Year] IN ([2013], [2014])  )AS unpvt ;

但我认为最好能够进入底层表结构,因为实际数据包含更多列,需要更多时间来处理。

带有示例数据的

Here's a Fiddle

希望你能告诉我一个到达那里的方法。 谢谢。

2 个答案:

答案 0 :(得分:8)

SELECT [ID],
       [RowNumber],
       [Year],
       Sales,
       Budget
FROM   mytable
       CROSS APPLY (VALUES (2013, [Sales 2013], [Budget 2013]),
                           (2014, [Sales 2014], [Budget 2014]) ) 
                     V([Year], Sales, Budget) 

SQL Fiddle

答案 1 :(得分:2)

一种方法是在解开后重新开始 - 就像这样:

select [Id], [Year], [Sales], [Budget], [Actual] from
(SELECT [Id],
        Left([Colhead], charindex(' ',[Colhead])-1) [Category],
        Right([Colhead], len([Colhead])-charindex(' ',[Colhead])) [Year],
        [Figures]
 FROM (SELECT * FROM mytable) p
       UNPIVOT ([Figures] FOR [Colhead] IN 
                ([Sales 2013],[Sales 2014],[Budget 2013],[Budget 2014],[Actual 2013],[Actual 2014])
      )
 AS unpvt) as u
pivot
(max([Figures]) for [Category] in ([Sales], [Budget], [Actual])) as p

SQLFiddle here