Using Microsoft SQL Server 2008 R2, I am trying to recursively join monthly data from 12 queries into 1 query and results table. I know how to join the results if I write out the query 12 times and join each one but the query is 16 lines long already, so I am looking for a way to do it recursively.
I will use a sales example:
I have a table with the following defintion
sales(ID int, EmpID int, dt datetime, amount numeric(5,2)).
With the following query, I get 12 tables, how do I join them all together on EmpID and how can I name the column header with the month/year:
DECLARE @mo INT, @yr INT
SET @mo = 1
SET @yr = YEAR(GETDATE())
WHILE (@mo < 13)
BEGIN
SELECT EmpID, SUM(numeric) AS Totals WHERE MONTH(dt) = @mo AND YEAR(dt) = @yr GROUP BY EmpID
SET @mo = @mo + 1
END
I would like the results to be something like:
EmpID 1-2012 2-2012 ... 12-2012
----- ------- ------- -------
1 XXXX.XX XXXX.XX XXXX.XX
...
100 XXXX.XX XXXX.XX XXXX.XX