【发布时间】:2018-10-26 00:08:20
【问题描述】:
我有多个表需要加入
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)
还有其他方法吗?
【问题讨论】:
标签: sql-server join group-by outer-join