2017-06-06 84 views
-1

我有兩個我需要加入的表。我有相同的列兩個SELECT語句除了OrderValueSalesTarget表A在SQL表中刪除表B中的行JOIN

SELECT 
    b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue 
FROM 
    dbo.vw_jab_Consolidated_Orders as b 
INNER JOIN 
    dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson 
WHERE 
    b.TrnYear = '2017' 
ORDER BY 
    a.TrnMonth 

SELECT 
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget 
FROM 
    dbo.vw_jab_SalTargets as a 
WHERE 
    a.TrnYear = '2017' AND a.SequenceType = 'BR' 
GROUP BY 
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget 

我的問題是,因爲有那裏有沒有OrderValues個月,該SalesTarget值被過濾掉了,當我加入這兩個表如下:

SELECT   
    a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales 
FROM 
    (SELECT   
     TrnYear, SUM(SalesTarget) AS SalesTarget 
    FROM    
     dbo.vw_jab_SalTargets 
    WHERE   
     (SequenceType = 'BR') 
    GROUP BY 
     SequenceType, TrnYear) AS A 
LEFT JOIN 
    (SELECT   
     TrnYear, SUM(ActualSales) AS InvoicedSales 
    FROM    
     dbo.vw_jab_Consolidated_Sales 
    GROUP BY 
     TrnYear) AS b ON a.TrnYear = b.TrnYear 
WHERE 
    a.TrnYear = '2017' 
GROUP BY 
    a.TrnYear 
+0

當你在這裏問一個問題時,不需要SHOUT :-) –

+0

你試過了「左連接」而不是「內連接」嗎? – user2023861

+0

嗨,我試過左連接。 – Jeannette

回答

0

你想要一個正確的外連接,而不是內連接。對於右外連接,即使左表中沒有匹配的值,右表的所有列也會保留。

試試這個:

SELECT  a.TrnYear, a.TrnMonth, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales 
    FROM   (SELECT  TrnYear, TrnMonth, SUM(SalesTarget) AS SalesTarget 
           FROM   dbo.vw_jab_SalTargets 
           WHERE  (SequenceType = 'BR') 
           GROUP BY SequenceType, TrnYear, TrnMonth) AS a RIGHT OUTER JOIN 
           (SELECT  TrnYear, TrnMonth, SUM(ActualSales) AS InvoicedSales 
            FROM   dbo.vw_jab_Consolidated_Sales 
            GROUP BY TrnYear, TrnMonth) AS b ON a.TrnYear = b.TrnYear and a.TrnMonth=b.TrnMonth 
            WHERE a.TrnYear = '2017' 
    GROUP BY a.TrnYear, a.TrnMonth 
    ORDER BY TrnMonth 
+0

這給出了一個很好的結果,但是這些值是不正確的 – Jeannette

+0

我相信問題是兩個表中都有值不存在於每個表中 – Jeannette

+0

明白了 - FULL OUTER JOIN - 感謝您的黃金比例和user2023861 – Jeannette

0

你可以切換到右連接,但當時如果你沒有InvoicedSales,你不會得到任何SalesTargets。我會使用一個FULL OUTER JOIN像這樣:

SELECT COALESCE(a.TrnYear,b.TrnYear) AS TrnYear 
    ,SUM(a.SalesTarget) AS SalesTarget 
    ,SUM(b.InvoicedSales) AS InvoicedSales 
FROM (
    SELECT TrnYear 
     ,SUM(SalesTarget) AS SalesTarget 
    FROM dbo.vw_jab_SalTargets 
    WHERE (SequenceType = 'BR') 
    GROUP BY SequenceType 
     ,TrnYear 
    ) AS a 
FULL OUTER JOIN (
    SELECT TrnYear 
     ,SUM(ActualSales) AS InvoicedSales 
    FROM dbo.vw_jab_Consolidated_Sales 
    GROUP BY TrnYear 
    ) AS b 
    ON a.TrnYear = b.TrnYear 
WHERE a.TrnYear = '2017' 
    OR b.TrnYear = '2017' 
GROUP BY COALESCE(a.TrnYear,b.TrnYear) 

聚結()是必要的,這樣的列將始終返回TrnYear。

+0

感謝所有的幫助,我得到了一個很好的結果。 – Jeannette