Reputation: 176
I have the below data in SQL:
Now, I would like to pivot it base on the "CostCenterNumber" field to obtain this:
Upvotes: 0
Views: 65
Reputation: 2016
Try this one:
DECLARE @cols as varchar(max)
DECLARE @sql as varchar(max)
SELECT @cols = coalesce(@cols + ',','') + '[' + CostCenterNumber + ']' FROM #MyTable
SET @sql =
'SELECT Year, GLClass, Code, GLDescription, ' + @cols + '
FROM (
SELECT *
FROM #MyTable
) as P
PIVOT
(
SUM(Total)FOR [CostCenterNumber] IN (' + @cols + ')
)AS pvt'
EXEC(@sql)
Upvotes: 2