SQL Server 2008 Unpivot将未知的列数转换为行

时间:2012-03-09 22:49:54

标签: sql sql-server-2008

原件:

EmpID     Week1     Week2    Week3...(Unknown unmber of weeks)
001       1         2        3
002       2         1        0
003       3         4        0

目标:

EmpID   Attibute    AttributeValue
001         Week1       1
001         Week2       2
001         Week3       3
002         Week1       2
002         Week2       1
002         Week3       0
003         Week1       3
003         Week2       4
003         Week3       0
             .
             .
             .
(will auto generate unknown # of weeks and their values)

我完成了我的作业,我没有找到像这样的问题。我发现的唯一一个是“Dynamic SQL Server Pivot ( UNPIVOT ) column name to a row value”。我试图运行该查询,但SQL Server没有返回结果,并且消息显示“命令已成功完成。”

2 个答案:

答案 0 :(得分:2)

好吧,您的表格中不能包含“未知”的列数,但请参阅Using PIVOT and UNPIVOT

SELECT EmpID, Attibute, AttributeValue
FROM 
   (SELECT EmpID, Week1, Week2, Week3
   FROM pvt) p
UNPIVOT
   (AttributeValue FOR Attibute IN 
      (Week1, Week2, Week3)
)AS unpvt

答案 1 :(得分:1)

假设您的表名为Emp,并且您要取消与Week%匹配的列:

declare @SQL nvarchar(max)

set @SQL = 
  N'select EmpID, Attribute, AttributeValue from Emp unpivot (AttributeValue for Attribute in ('+
  stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('Emp') and
               C.name like 'Week%'
         for xml path('')), 1, 1, '')+
  N')) as U order by EmpID, Attribute'

exec (@SQL)