zXSwordXz
zXSwordXz

Reputation: 176

SQL Pivot Query

I have the below data in SQL: enter image description here

Now, I would like to pivot it base on the "CostCenterNumber" field to obtain this: enter image description here

Upvotes: 0

Views: 65

Answers (2)

Rigel1121
Rigel1121

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

user4509170
user4509170

Reputation:

I suggest you to use where and between condition from your query

Upvotes: 1

Related Questions