fraser jordan
fraser jordan

Reputation: 114

How to assign column names to a pivot table

Heres my statement

SELECT *
FROM(
SELECT CAST([School ID] as varchar(10)) AS 'School ID', Year, Value as [Total]
FROM [sandbox].[dbo].[SchoolInformation]
WHERE Attribute = 'Total' AND Year IN ('2010','2011','2012','2013','2014')

)cte
PIVOT (SUM([Total]) FOR YEAR IN([2010],[2011],[2012],[2013],[2014]))pvt

My question is, is there a way to change the column names to show (year1,year2,year3,year4,year5) instead of (2010,2011,2012,2013,2014)?

Thanks :)

Upvotes: 0

Views: 75

Answers (1)

Biscuits
Biscuits

Reputation: 1807

You can alias your columns, like this.

SELECT
    [2010] AS 'year1',
    [2011] AS 'year2',
    ....
FROM (
    SELECT ...
) ...

Another way I can think of involves writing dynamic SQL.

Upvotes: 1

Related Questions