外部加入团队

时间:2018-05-16 04:13:53

标签: sql-server join group-by outer-join

我有一个需要加入的多个表

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

我创建了一个新的临时表,所以我可以加入

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)

其他任何方式吗?

1 个答案:

答案 0 :(得分:1)

尝试以下查询,

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