New to SQL Pivot and Dynamic SQL. I have a table with a column that I would like to make the distinct attributes become column headings in a pivot table, while also creating correct major categories for an additional column about the main data, and report a score in those fields. Problem is I can't get the scores to populate correctly or the distinct column headings.
I can't get the Measure1 fields to become column headings and I can't get the scores to populate. With the correct [measure name] related to the Measure1 and associated score. Thanks for any help in advance.
Declare @ColumnNames NVARCHAR (MAX) = ''
Declare @SQL NVARCHAR (MAX)= ''
Select @ColumnNames += QUOTENAME([Measure1]) + ','
From [dbo].[Table1]
Group By [Measure1]
SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1)
SET @SQL =
'Select * FROM
(Select
case
When [measure1] like ''%lower%'' then ''Lower''
When [measure1] like ''%upper%'' then ''Upper''
When [measure1] like ''%Days%'' then ''Days''
When [measure1] like ''%Occur%'' then ''Occurrences''
When [measure1] like ''%Pred%'' then ''Predicted''
When [measure1] like ''%Ratio%'' then ''Ratio''
end as [Measure1]
,case
When [Measure Name] like ''%Tewksbury%'' then ''Stan''
When [Measure Name] like ''%Boston%'' then ''Steve''
When [Measure Name] like ''%Seattle%'' then ''Payton''
When [Measure Name] like ''%Denver%'' then ''Lavell''
When [Measure Name] like ''%Houston%'' then ''Caren''
When [Measure Name] like ''%Hudson%'' then ''Michael''
end as Measure_Category
,[Main ID] AS [Cust ID]
,[Compared to Average]
,[score]
From
[dbo].[Table1]
) AS BaseData
PIVOT (
MAX([Compared to Average])
FOR [measure1]
IN (' + @ColumnNames +
')) AS PivotTable'
Execute sp_executesql @SQL


