Skip to content

Instantly share code, notes, and snippets.

@TomerAdmon
Created December 28, 2016 20:42
Show Gist options
  • Save TomerAdmon/f9d74c7bf308026c1e4684b942e1b077 to your computer and use it in GitHub Desktop.
Save TomerAdmon/f9d74c7bf308026c1e4684b942e1b077 to your computer and use it in GitHub Desktop.
Create a new table with pivoted data from the original table
declare
@cols nvarchar(max),
@sele nvarchar(max),
@stmt nvarchar(max)
select @cols = isnull(@cols + ', ', '') + '[' + T.ReleasedVersion + ']' from (select distinct ReleasedVersion from DriversAndLibraries Where ReleasedVersion <> '') as T
select @sele = isnull(@sele + ', ', '') + 'max([' + T.ReleasedVersion + ']) AS ' + '[' + T.ReleasedVersion + ']' from (select distinct ReleasedVersion from DriversAndLibraries Where ReleasedVersion <> '') as T
PRINT @sele
select @stmt = '
WITH Pivoted AS
(
select * from DriversAndLibraries a
pivot (
max(FileVersion) for ReleasedVersion in (' + @cols + ')
) as max
)
SELECT FileName, ' + @sele + ' into SummaryDriversTable from Pivoted
group by FileName
Order by Pivoted.FileName
'
PRINT @stmt
exec sp_executesql @stmt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment