Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using MS SQL SERVER 2008 and I want to convert following dynamic pivot query into static pivot

SQL
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Weeks) 
                    from MyTestTable
                    group by Weeks
                    order by Weeks
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Month_year,' + @cols + ' from 
             (
                select Month_year, weeks, Xcount
                from MyTestTable
            ) x
            pivot 
            (
                sum(xCount)
                for Weeks in (' + @cols + ')
            ) p '
execute(@query);


Please help me.

What I have tried:

I have tried to make following query but occurs error in "For weeks in ()" pivot statement (last to lines of query).

SQL
SELECT Month_year,STUFF((SELECT ',' + QUOTENAME(Weeks) from MyTestTable group by Weeks
     order by Weeks FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
             from 
             (
                select Month_year, weeks, Xcount
                from MyTestTable
            ) x
            pivot 
            (
                sum(xCount)
                for Weeks in (STUFF((SELECT ',' + QUOTENAME(Weeks) from MyTestTable group by Weeks
     order by Weeks FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''))
            ) p 
Posted
Comments
jaket-cp 6-Jul-18 4:10am    
print it and you can see the final static query

print @query;
Pankaj sonar 6-Jul-18 4:43am    
After print the query, the output is changed. I want to show the columns (using stuff function) are dynamically not static.
jaket-cp 6-Jul-18 4:54am    
oh right - you want the query to get dynamic columns to put in the pivot query.
From my understanding it is not possible.
if you do a google search http://lmgtfy.com/?q=tsql+dynamic+pivot+columns
you will see that is how it is done

I use similar technique to do dynamic pivots.
Pankaj sonar 6-Jul-18 5:47am    
Thank you for suggestion. I already done which is you suggested. I want to create static query from dynamic query and used this query to bind data to gridview.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900