我有一个带有列的表:
Anno, Description, Number
________________________
2011 Example1 12
2013 Example2 9
2011 Example4 8
……
列中的值Description
是动态的
我必须制作一个像这样的表格:
Anno Example1 Example2 Example3 Example4 ........
--------------------------------------------------
2011 12 0 0 8 ........
2012 0 23 24 36 ........
......
我创建了一个这样的视图:
Declare @cols AS NVARCHAR(Max),
@query AS NVARCHAR(Max)
Select @cols = STUFF(( Select ','+QUOTENAME(Description)
FROM mytable
GROUP BY Description
Order by Description
FOR XML PATH ('',TYPE
).value('.','NVARCHAR(Max)'),1,1,'')
SET @query= 'Select Anno, '+cols+' from
(Select Anno, Description, Number
FROM mytable ) as x
PIVOT
(
SUM(Number)
FOR Description in ('+cols+')
) pvt'
EXECUTE(@query)
它返回一个错误:
',' 附近的语法不正确