to do dynamic pivot I did it a long way back.
UPDATED: Made more close to your code and talble names.
This will work for however many columns you want for the PIVOT, doesnt matter if 1 or 20
DECLARE @SelectFieldNameList as varchar(8000)
DECLARE @SelectFieldNameListCount as varchar(8000)
Set @SelectFieldNameList = ''
Set @SelectFieldNameListCount = ''
-- this section selects the list of firm location names and puts them in a string to be used in the pivot
-- it does it for the field select list and the count select using ISNULL so it puts a 0 if no counts returned
SELECT top (999999) @SelectFieldNameList = @SelectFieldNameList + case when @SelectFieldNameList = '' then '' else ', ' end
+ '[' + Data + ']',
@SelectFieldNameListCount = @SelectFieldNameListCount + case when @SelectFieldNameListCount = '' then '' else ', ' end
+ 'ISNULL([' + Data + '], ''0'')' + Data
From TableName
Where Data IS NOT NULL AND Ltrim(Data) <> ''
Group by Data
-- just for testing
select @SelectFieldNameList, @SelectFieldNameListCount
-- NOW USE THE ABOVE TO get the data pivoted with your dyanic fields
EXEC('
SELECT [Code], ' + @SelectFieldNameListCount + '
FROM (
SELECT [Code], Data, Sum(CountTotal) as CountTotal
From TableName
Group by [Code], Data
) AS TableToBePivoted
PIVOT (
SUM(CountTotal)
FOR Data IN (' + @SelectFieldNameList + ')
) AS PivotedTable
order by [Code];
')