You could transfer all distinct month into XML, then use it in pivot
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.month)
FROM #monthly_sales c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,' ')
set @query = 'SELECT empid, ' + @cols + ' from
(
select empid
, amount
, month
from #Monthly_sales
) x
pivot
(
max(amount)
for month in (' + @cols + ')
) p '
EXEC (@query)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…