SQL Server T-SQL PIVOT is a great feature that you can turn the unique values from one column into multiple into multiple columns in the output table result. It also works great if you can iterate all unique values in the column to be pivoted , but the problem is that sometimes you don't know that information, or you have multiple unique values which is difficult to list all of them in the query.
With help from my friend (many thanks to Stephanie), it is easy to address this problem using FOR XML PATH. Here is an example based on AdvenutreWorks2012 sample database:
set nocount on;
-- For each product sub category, get avergae cose for differnt DaysToManufacture
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(p.DaysToManufacture)
FROM Production.Product as p
FOR XML PATH(''), TYPE
set @query = 'SELECT ProductSubcategoryID, ' + @cols + ' from
from Production.Product as p
where p.ProductSubcategoryID IS NOT NULL
for DaysToManufacture in (' + @cols + ')
) p '
Hope it helps!