Created
December 10, 2015 21:02
-
-
Save mbourgon/9e0d19f11c84dbcf024d to your computer and use it in GitHub Desktop.
Dynamic Pivot using T-SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @SQL as VARCHAR (MAX) | |
DECLARE @Columns AS VARCHAR (MAX) | |
SELECT @Columns= | |
COALESCE(@Columns + ',','') + QUOTENAME(across) | |
FROM | |
( | |
SELECT DISTINCT across | |
From #TEMP | |
) AS B | |
ORDER BY B.across | |
SET @SQL=' | |
SELECT down, ' + @Columns + ' FROM | |
( | |
SELECT down, across, the_count FROM | |
#TEMP ) AS source | |
PIVOT | |
(SUM(the_count) FOR source.across IN (' + @columns + ') | |
)AS pvt' | |
EXEC (@sql) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment