There are a few confusing things that you are doing.
First, typically you will unpivot multiple columns. Right now, you are are unpivoting one column and it seems like you are doing it just to rename the column?
Second, you are aggregating the data twice, the PIVOT should be able to handle the aggregation using SUM()
.
Third, it is not exactly clear on why you need the column headers as a row, what will you want the column headers to be called?
Based on your sample data you should be able to just apply the PIVOT function:
select 'TotalRecords' TotalRecords,
[2012],
[2013],
[All]
from tbleirstatisticsoverviewsummary
pivot
(
sum(totalrecords)
for FiscalYear IN ([2012],[2013],[ALL])
) p;
See SQL Fiddle with Demo. Then if you want a row with the columns headers, then you can use a UNION ALL:
select 'colname' col1,
2012 col2,
2013 col3,
'All' col4
union all
select 'TotalRecords' TotalRecords,
[2012],
[2013],
[All] = cast([all] as varchar(10))
from tbleirstatisticsoverviewsummary
pivot
(
sum(totalrecords)
for FiscalYear IN ([2012],[2013],[ALL])
) p;
See SQL Fiddle with Demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…