[英]Dynamic Pivot Table by Month
I'm trying to create a dynamic pivot table in SQL that will report based on month and year.我正在尝试在 SQL 中创建一个动态 pivot 表,该表将基于月份和年份进行报告。 I did a bunch of research and was able to come up with the below query:
我做了很多研究,并能够提出以下查询:
declare @dynamic nvarchar(max),
@column nvarchar(max);
set @column = N'';
select @column += N'' + datename(month,incurdate) +' '+ datename(year,incurdate) + ','
from (select distinct a.incurdate from artable a) as Transpose
select @column = substring(@column,0,len(@column))
set @dynamic = 'select * from
(
select month, incurdate, dolamount
from artable join dolentry on month = period
) b
pivot(sum(dolamount) for incurdate in (' + @column + ')) as PivotTable'
execute sp_executesql @dynamic
I am able to print the @column variable successfully, but the problems happen when I try to set it in the @dynamic variable.我能够成功打印@column 变量,但是当我尝试在@dynamic 变量中设置它时会出现问题。 The error message is ' Msg 102, Level 15, State 1, Line 6 Incorrect syntax near '1990'.
错误消息是'消息 102,级别 15,State 1,第 6 行'1990' 附近的语法不正确。 ' 1990 is the first year of the first pivoted column.
' 1990 年是第一个枢轴柱的元年。 Any help or tips are appreciated.
任何帮助或提示表示赞赏。 Thanks!
谢谢!
You need to use QUOTENAME in the following code:您需要在以下代码中使用QUOTENAME :
select @column += N'' + QUOTENAME(datename(month,incurdate) +' '+ datename(year,incurdate)) + ','
from (select distinct a.incurdate from artable a) as Transpose
in order to get output like this:为了像这样获得 output :
[col01], [col02], [col03], ... , [col04]
As you can see from the docs , the PIVOT
syntax requires the pivoting columns to be wrapped in square brackets:正如您从文档中看到的那样,
PIVOT
语法要求将旋转列括在方括号中:
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.