按月份列出的动态透视表

ef1yzkbh  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(421)

我尝试在sql中创建一个动态透视表,它将基于月份和年份进行报告。我做了一系列研究,得出了以下问题:

  1. declare @dynamic nvarchar(max),
  2. @column nvarchar(max);
  3. set @column = N'';
  4. select @column += N'' + datename(month,incurdate) +' '+ datename(year,incurdate) + ','
  5. from (select distinct a.incurdate from artable a) as Transpose
  6. select @column = substring(@column,0,len(@column))
  7. set @dynamic = 'select * from
  8. (
  9. select month, incurdate, dolamount
  10. from artable join dolentry on month = period
  11. ) b
  12. pivot(sum(dolamount) for incurdate in (' + @column + ')) as PivotTable'
  13. execute sp_executesql @dynamic

我能够成功地打印@column变量,但是当我尝试在@dynamic变量中设置它时,问题就出现了。错误消息是'1990'附近的'msg 102,level 15,state 1,line 6语法错误。'1990是第一个数据透视列的第一年。任何帮助或提示都将不胜感激。谢谢!

tkqqtvp1

tkqqtvp11#

您需要在以下代码中使用quotename:

  1. select @column += N'' + QUOTENAME(datename(month,incurdate) +' '+ datename(year,incurdate)) + ','
  2. from (select distinct a.incurdate from artable a) as Transpose

为了得到这样的输出:

  1. [col01], [col02], [col03], ... , [col04]

从文件中可以看出 PIVOT 语法要求旋转列用方括号括起来:

  1. SELECT <non-pivoted column>,
  2. [first pivoted column] AS <column name>,
  3. [second pivoted column] AS <column name>,
  4. ...
  5. [last pivoted column] AS <column name>
  6. FROM
  7. (<SELECT query that produces the data>)
  8. AS <alias for the source query>
  9. PIVOT
  10. (
  11. <aggregation function>(<column being aggregated>)
  12. FOR
  13. [<column that contains the values that will become column headers>]
  14. IN ( [first pivoted column], [second pivoted column],
  15. ... [last pivoted column])
  16. ) AS <alias for the pivot table>
  17. <optional ORDER BY clause>;
展开查看全部

相关问题