Went to MSDN and back, yet am still confused as ever on how to use the pivot function. How I transform the following code to transfer the rows to columns?
SELECT
YEAR(hiredate) AS Year, COUNT(*) AS Count
FROM
Faculty
GROUP BY
YEAR(hiredate)
Went to MSDN and back, yet am still confused as ever on how to use the pivot function. How I transform the following code to transfer the rows to columns?
SELECT
YEAR(hiredate) AS Year, COUNT(*) AS Count
FROM
Faculty
GROUP BY
YEAR(hiredate)
Something like this should do it:
SELECT pvt.[2010], pvt.[2011], pvt.[2012], pvt.[2013], pvt.[2014]
FROM ( SELECT [Year] = DATEPART(YEAR, HireDate), V = 1
FROM Faculty
) AS f
PIVOT
( COUNT(V)
FOR [Year] IN ([2010], [2011], [2012], [2013], [2014])
) AS pvt;
PIVOT
does not allow you to use a function on the column to pivoted (e.g. YEAR(HireDate)
), nor does it allow COUNT(*)
so you need to put the function into a subquery, and also create a column to use to count (V
in this example).