我使用的是AdventureWorks數據庫和SQL Server 2012的T-SQL食譜書,開始學着在下面的例子麻煩:表子集比較
我不得不從Sales.SalesPersonQuotaHistory檢查SalesQuota在2007年和2008年。
SELECT sp.BusinessEntityID
, SUM(s2008.SalesQuota) AS '2008'
, SUM(S2007.SalesQuota) AS '2007'
FROM Sales.SalesPerson sp
LEFT OUTER JOIN Sales.SalesPersonQuotaHistory s2008
ON sp.BusinessEntityID = s2008.BusinessEntityID
AND YEAR(s2008.QuotaDate) = 2008
LEFT OUTER JOIN Sales.SalesPersonQuotaHistory s2007
ON sp.BusinessEntityID = s2007.BusinessEntityID
AND YEAR(s2007.QuotaDate) = 2007
GROUP BY sp.BusinessEntityID
首先結果是:
BusinessEntityID 2008 2007
---------------- --------------------- ---------------------
274 1084000.00 1088000.00
275 6872000.00 9432000.00
276 8072000.00 9364000.00
277 6644000.00 8700000.00
就像書上說的。
但後來我試着用下面的查詢,以獲得2008 SalesQuota:
SELECT sp.BusinessEntityID,
SUM(spqh.SalesQuota) AS '2008'
FROM Sales.SalesPerson sp
LEFT JOIN Sales.SalesPersonQuotaHistory spqh
ON sp.BusinessEntityID = spqh.BusinessEntityID
AND YEAR(spqh.QuotaDate) = 2008
GROUP BY sp.BusinessEntityID
,並得到這個:
BusinessEntityID 2008
---------------- ---------------------
274 271000.00
275 1718000.00
276 2018000.00
277 1661000.00
我在做什麼錯在這裏?我想我錯過了那些左連接點的東西,但我無法弄清楚什麼。
這一次給出了相同的結果:
SELECT BusinessEntityID
, SUM(SalesQuota) AS '2008'
FROM Sales.SalesPersonQuotaHistory
WHERE YEAR(QuotaDate) = 2008
GROUP BY BusinessEntityID
BusinessEntityID 2008
---------------- ---------------------
274 271000.00
275 1718000.00
276 2018000.00