I have this SQL query which groups searches by month:
; with Mth (st, nd) as (
select DATEADD (M, datediff (m, 0,'2012-09-01'), 0),
DATEADD (M, DATEDIFF (m, 0, '2012-09-01') + 1, 0)
union all
select DATEADD (m, 1, st),
DATEADD (m, 1, nd)
from Mth
where nd <= DATEADD (m, datediff (m, 0, getdate()), 0)
)
select MONTH(Mth.st) Month,
COUNT(S.QRY_ID) Searches
FROM Mth
LEFT JOIN SEARCHES S
on Mth.st <= S.CREATED
and Mth.nd > S.CREATED
GROUP BY YEAR(Mth.st), MONTH(Mth.st)
ORDER BY 1,2
The result appears like this:
Month | Searches
---------------------
9 | 21
10 | 32
11 | 18
I’m trying to figure out how to use PIVOT to achieve this:
9 | 10 | 11
-----------------------
21 | 32 | 18
Could anyone please explain to me how to do it?
You can use something like this:
See SQL Fiddle with Demo
If you have an unknown number of months to transform, then you can use dynamic sql similar to this:
See SQL Fiddle with Demo