Skip to content
Advertisement

Dynamic Pivot Table by Month

I’m trying to create a dynamic pivot table in SQL that will report based on month and year. I did a bunch of research and was able to come up with the below query:

I am able to print the @column variable successfully, but the problems happen when I try to set it in the @dynamic variable. The error message is ‘Msg 102, Level 15, State 1, Line 6 Incorrect syntax near ‘1990’.‘ 1990 is the first year of the first pivoted column. Any help or tips are appreciated. Thanks!

Advertisement

Answer

You need to use QUOTENAME in the following code:

in order to get output like this:

As you can see from the docs, the PIVOT syntax requires the pivoting columns to be wrapped in square brackets:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement