3

我有一个带有列的表:

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)

它返回一个错误:

',' 附近的语法不正确

4

2 回答 2

2

试试这个——

DECLARE @query NVARCHAR(MAX)

SELECT @query = '
    SELECT Anno, ' + cols + ' 
    FROM (
        SELECT Anno, Description, Number
        FROM dbo.mytable 
    ) x
    PIVOT
    (
    SUM(Number) FOR [Description] IN (' + cols + ')
    ) pvt'
FROM (
    SELECT cols = STUFF((
        SELECT ', [' + [Description] + ']'
        FROM dbo.mytable d
        GROUP BY [Description]
        ORDER BY [Description]
        FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
) t

EXEC sys.sp_executesql @query
于 2013-05-31T04:30:53.807 回答
1

几个小的语法错误。首先,您在FOR XML PATH.

FOR XML PATH ('',TYPE

变成

FOR XML PATH (''),TYPE

其次,您将列列表存储在一个变量中,而不是将其作为动态 SQL 中的一个引用。这可以正常工作。

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+', Total from
             (Select Anno, Description, Number, 
                SUM(Number) OVER (PARTITION BY Anno) AS Total
              FROM mytable ) as x
              PIVOT
              (
                SUM(Number)
                FOR Description in ('+@cols+')
               ) pvt'

SQL 小提琴

于 2013-05-30T15:55:12.823 回答