2015-10-30 101 views
1

我使用的是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 

回答

1

您的第一個查詢可能是創建結果的笛卡爾積。相反,我會使用條件的聚合,從而獲得兩個值(它應該符合你的第二個查詢):

SELECT sp.BusinessEntityID, 
    SUM(CASE WHEN Year(spqh.QuotaDate) = 2007 then spqh.SalesQuota end) AS '2007', 
    SUM(CASE WHEN Year(spqh.QuotaDate) = 2008 then spqh.SalesQuota end) AS '2008' 
FROM Sales.SalesPerson sp 
    LEFT JOIN Sales.SalesPersonQuotaHistory spqh 
     ON sp.BusinessEntityID = spqh.BusinessEntityID 
GROUP BY sp.BusinessEntityID 
1

我不認爲你第一個例子是正確的。

SELECT sp.BusinessEntityID, 
     SUM(CASE WHEN YEAR(s.QuotaDate) = 2007 THEN s.SalesQuota ELSE 0 END) AS '2007', 
     SUM(CASE WHEN YEAR(s.QuotaDate) = 2008 THEN s.SalesQuota ELSE 0 END) AS '2008' 
FROM Sales.SalesPerson sp 
LEFT JOIN Sales.SalesPersonQuotaHistory s ON sp.BusinessEntityID = s.BusinessEntityID 
GROUP BY sp.BusinessEntityID 
1

如果不從Sales.SalesPerson表返回任何列,您可以排除它,並使用pivot,讓您的預期結果:

select 
    BusinessEntityID, 
    [2008], 
    [2007] 
from (
     select 
      BusinessEntityID, 
      year(QuotaDate) as SalesQuotaYear, 
      sum(SalesQuota) as SalesQuota 
     from Sales.SalesPersonQuotaHistory 
     where year(QuotaDate) in(2007,2008) 
     group by BusinessEntityID, 
      year(QuotaDate) 
     ) as t 
    pivot (
      sum(SalesQuota) 
      for SalesQuotaYear in([2007],[2008]) 
      ) as p