SQL - 使用pivot命令时出错

时间:2015-12-29 20:24:47

标签: sql sql-server tsql pivot

我在使用pivot命令时遇到问题 - 我收到以下错误

  

“无效的列名称'2013-03-22'。无效的列名'2013-03-29'。无效的列名'2013-04-05'。列名称'卷'无效。列名无效'周末结束日期”“。

运行此代码时

SELECT * 
FROM
(
   SELECT [Area], 
     [Region], 
     [Channel], 
     [Controller], 
     [2013-03-22] AS _dt1, 
     [2013-03-29] AS _dt2, 
     [2013-04-05] AS _dt3 
  FROM [DataTable]
) AS SourceTable
PIVOT
(
   SUM ([Volume]) 
   FOR [Week Ending Date] IN ([2013-03-22], [2013-03-29], [2013-04-05])
) AS PivotTable

它似乎符合正确的格式..任何想法?

2 个答案:

答案 0 :(得分:2)

似乎源表不应包含要转动的列的值,但包含包含要转动的值和要转动的值的列。见下文:

SELECT [Area], 
[Region], 
[Channel], 
[Controller],
[2013-03-22] as _dt1, 
[2013-03-29] as _dt2, 
[2013-04-05] as _dt3
FROM 
(
SELECT [Area], 
[Region], 
[Channel], 
[Controller], 
[Volume],
[Week Ending Date]
FROM [DataTable]
) AS SourceTable 
PIVOT(SUM ([Volume]) FOR [Week Ending Date] IN ([2013-03-22], [2013-03-29], 
[2013-04-05])) 
AS PivotTable

答案 1 :(得分:0)

通常我动态地使用数据透视表列然后运行执行sp_executesql @query

  1. 找到截然不同的日期' 2013-03-22' ...然后把它变成字符串 使用STUFF和XML PATH

  2. 将其替换为嵌入式SQL查询

  3. 所以你永远不会难以对你的专栏进行编码

    这里有我的例子

     DECLARE @cols AS NVARCHAR(MAX),   @query  AS NVARCHAR(MAX)
       select @cols = STUFF((SELECT  N',' + QUOTENAME(c.name) 
       FROM sys.tables AS t
       INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
       WHERE t.name = 'tagCloudLibrary'
        and c.name not in ('langID')
        FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')  ,1,1,'')
    
    
        set @query = N'SELECT ' + @cols + N' from tagCloudLibrary'
        execute sp_executesql @query;
    

    如果你的PIVOT是正确的,请在正确处理STUFF的条款......

      DECLARE @cols AS NVARCHAR(MAX),   @query  AS NVARCHAR(MAX)
       select @cols = STUFF((SELECT top 10  N',' + QUOTENAME(LastActivityDate)  
       FROM DataTable   
         FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')  ,1,1,'')
    
         select @cols
    
         set query = N'SELECT * FROM
          (SELECT [Area], [Region], [Channel], [Controller], ' +  @cols 
         + N' FROM [DataTable]) AS SourceTable '
        + N' PIVOT  (SUM ([Volume]) FOR [Week Ending Date] IN (' +  @cols  + ') AS PivotTable '
    
         execute sp_executesql @query;