2013-11-22 169 views
1

使用Microsoft SQL Server 2008 R2,我試圖遞歸地將12個查詢的每月數據連接到1個查詢和結果表中。我知道如何連接結果,如果我寫出12次查詢並加入每個查詢,但查詢已經有16行,所以我正在尋找一種遞歸的方式。Microsoft SQL Server - 遞歸連接

我將使用一個銷售例如:
我有一個表具有以下確定指標

sales(ID int, EmpID int, dt datetime, amount numeric(5,2)). 

用下面的查詢,我得到12桌,我該如何加入他們一起上的EmpID哪有我的名字列標題與月/年:

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 

我想結果是這樣的:

EmpID  1-2012  2-2012 ... 12-2012 
-----  ------- -------   ------- 
1   XXXX.XX XXXX.XX   XXXX.XX 
... 
100  XXXX.XX XXXX.XX   XXXX.XX 
+0

你可以提供更多的信息,我不明白12桌來自哪裏。 – Juan

回答

1

你可以閱讀關於遞歸公用表表達式。 EG:

;WITH Months AS 
(
    SELECT 1 as [Month] 

    UNION ALL 

    SELECT [Month] + 1 
    FROM Months 
    WHERE [Month] + 1 < 13 
), 
SELECT [Month] 
FROM Months 

但我想你正在尋找數據透視運算符。 EG:

;WITH SalesByMonth AS (
    SELECT 
     EmpID 
    ,MONTH(dt) AS Month 
    ,SUM(Amount) AS Total 
    FROM 
     @sales 
    WHERE 
     YEAR(dt) = @Year 
    GROUP BY 
     EmpID 
    ,MONTH(dt) 
) 
SELECT 
    EmpID, [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12] 
FROM (
    SELECT 
    EmpID 
    ,Month 
    ,Total 
    FROM 
    SalesByMonth) up 
PIVOT (SUM(Total) FOR Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) AS pvt 
ORDER BY 
    EmpID 

查看SQLFiddle示例here