外部加入组

Outer Join with Group

我有多个 table 需要加入

Customers (CustomerID int, CustomerName varchar(255))
Purchases (CustomerID int, PurchaseDate DateTime, Amt int)

我的查询是这样的

SELECT C.CustomerID, C.CustomerName, Year(P.PurchaseDate), Month(P.PurchaseDate), Sum(P.Amt)
FROM Customers C INNER JOIN Purchases P ON C.CustomerID = P.CustomerID
GROUP BY C.CustomerID, C.CustomerName, Year(P.PurchaseDate), Month(P.PurchaseDate)

结果是这样的

CustomerID CustomerName Year Month Amt
1001       Tom          2018 04    200
1001       Tom          2018 01    100
1001       Tom          2017 10    300
1001       Tom          2017 08    400
1002       Matt         2018 03    150
1002       Matt         2018 02    250
1002       Matt         2017 11    350
1002       Matt         2017 08    450
1003       John         2018 04    105
1003       John         2018 03    205
1003       John         2018 02    305
1003       John         2017 12    405

至此一切正常

但我实际上想要显示所有月份,即使没有数据

CustomerID CustomerName Year Month Amt
1001       Tom          2018 04    200
1001       Tom          2018 03    0
1001       Tom          2018 02    0
1001       Tom          2018 01    100
1001       Tom          2017 12    0
1001       Tom          2017 11    0
1001       Tom          2017 10    300
1001       Tom          2017 09    0
1001       Tom          2017 08    400
1002       Matt         2018 04    0
1002       Matt         2018 03    150
1002       Matt         2018 02    250
1002       Matt         2018 01    0
1002       Matt         2017 12    0
1002       Matt         2017 11    350
1002       Matt         2017 10    0
1002       Matt         2017 09    0
1002       Matt         2017 08    450

我创建了一个新临时 table 以便我可以加入

DECLARE @Cal AS TABLE (CalYear int , CalMonth int)
INSERT INTO @Cal (CalYear, CalMonth)
VALUES(2018,4)

INSERT INTO @Cal (CalYear, CalMonth)
VALUES(2018,3)

INSERT INTO @Cal (CalYear, CalMonth)
VALUES(2018,2)

...

问题是当我在之前的查询中加入@Cal 时,我没有为每个客户提供所有月份!!

我试过了

SELECT C.CustomerID, C.CustomerName, Year(P.PurchaseDate), Month(P.PurchaseDate), Sum(P.Amt)
FROM Customers C INNER JOIN Purchases P ON C.CustomerID = P.CustomerID
RIGHT OUTER JOIN @Cal L ON L.CalYear = Year(P.PurchaseDate) AND L.CalYear = Month(P.PurchaseDate)
GROUP BY C.CustomerID, C.CustomerName, Year(P.PurchaseDate), Month(P.PurchaseDate)

还有其他方法吗?

试试下面的查询,

SELECT  C.CustomerID, C.CustomerName, L.CalYear, L.CalMonth, Sum(P.Amt)
FROM    Customers   C
    CROSS JOIN @Cal L
    LEFT OUTER JOIN Purchases P ON  C.CustomerID =  P.CustomerID
                                AND L.CalYear    =  Year(P.PurchaseDate) 
                                AND L.CalMonth    =  Month(P.PurchaseDate)
GROUP BY C.CustomerID, C.CustomerName, L.CalYear, L.CalMonth