2009-07-08 46 views
3

我有兩個表,一個用我所有的分行,以及一個用我所有的銷售。銷售表還包含銷售代表ID,分行代碼,月份和年份。T-SQL,零和的不匹配上加入

我需要一個查詢將返回一個特定代表的銷售總額爲一年,由分公司和月份分組,查詢必須返回0,如果出現了在該月的一個分支沒有銷售。我有以下,沒有返回0,如果沒有銷售:

SELECT 
    s.Month, 
    b.BranchName, 
    SUM(s.InvoiceAmount) AS 'Sales' 
FROM 
    Branch b 
INNER JOIN 
    Sales s ON s.BranchID = b.BranchID 
WHERE 
    s.Year = 2008 
AND 
    s.SalesRepID= 11 
GROUP BY 
    s.Month, 
    b.BranchName 
ORDER BY 
    s.Month, 
    b.BranchName 
+0

您是否缺少SELECT列表中的s.Month? – pjp 2009-07-08 14:18:48

+0

我的錯誤,是在s.Month是SELECT – staterium 2009-07-08 14:27:51

+0

(在OP修正) – staterium 2009-07-08 14:32:19

回答

4

你需要添加「丟失」的數據,以便能夠加入。

SELECT 
    b.BranchName, 
    SUM(ISNULL(s.InvoiceAmount, 0)) AS 'Sales', 
    s.Month 
FROM 
    Branch b 
    LEFT OUTER JOIN (
      SELECT 
     b.BranchID AS BranchID 
     , s.SalesRepID AS SalesRepID 
     , Months.Month AS Month 
     , Years.Year AS Year 
     , 0 AS InvoiceAmount 
     FROM 
      Sales s 
      CROSS JOIN (
      SELECT 1 AS Month 
      UNION ALL SELECT 2 
      UNION ALL SELECT 3 
      UNION ALL SELECT 4 
      UNION ALL SELECT 5 
      UNION ALL SELECT 6 
      UNION ALL SELECT 7 
      UNION ALL SELECT 8 
      UNION ALL SELECT 9 
      UNION ALL SELECT 10 
      UNION ALL SELECT 11 
      UNION ALL SELECT 12 
      ) Months 
      CROSS JOIN (
      SELECT 2007 AS Year 
      UNION ALL SELECT 2008 
      UNION ALL SELECT 2009 
      ) Years 
      CROSS JOIN Branch b 
     UNION ALL SELECT 
     s.BranchID AS BranchID 
     , s.SalesRepID AS SalesRepID 
     , s.Month AS Month 
     , s.Year AS Year 
     , s.InvoiceAmount AS InvoiceAmount 
     FROM Sales s  
    )s ON s.BranchID = b.BranchID  
WHERE 
    s.Year = 2008 
    AND s.SalesRepID= 11 
GROUP BY 
    s.Month, 
    b.BranchName 
ORDER BY 
    b.BranchName, 
    s.Month 
2

你需要做一個LEFT JOIN來銷售,這樣才能返回,甚至沒有在任何記錄的代表銷售表。

+0

LEFT JOIN沒有銷售出現在最終的查詢,然後彙總將返回他們應該添加這些分支。 – Spence 2009-07-08 14:18:22

+0

-1 s.SalesRepId上有一個where子句,因此銷售中的左外連接將毫無意義。 – pjp 2009-07-08 14:51:00

1

如果您的查詢返回NULL,則可以使用聚結方法之一:COALESCE(SUM(...), 0)將返回列表中的第一個非NULL值...

0

我改變來自內部的連接到左外,並加入沒有銷售的分行的ISNULL功能。

SELECT 

    b.BranchName, 
    s.Month, 
    SUM(ISNULL(s.InvoiceAmount,0)) AS 'Sales' 
FROM 
    Branch b 
LEFT JOIN 
    Sales s ON s.BranchID = b.BranchID 
WHERE 
    s.Year = 2008 
AND 
    s.SalesRepID= 11 
GROUP BY 
    s.Month, 
    b.BranchName 
ORDER BY 
    s.Month, 
    b.BranchName 
0

你需要使用一個左連接和ISNULL得到的總和權:

SELECT b.BranchName 
, SUM(isnull(s.InvoiceAmount, 0)) AS 'Sales' 
FROM  Branch b 
LEFT JOIN Sales s ON s.BranchID = b.BranchID 
GROUP BY  s.Month, b.BranchName 
ORDER BY  s.Month, b.BranchName 

你仍然需要用它做更多的工作,以獲得個月呈現太多,如果一個推銷員有在特定月份沒有銷售。