表A在SQL JOIN中删除表B中的行

时间:2017-06-06 12:49:25

标签: sql join

我有两张桌子需要加入。除了OrderValueSalesTarget之外,我有两个具有相同列的select语句:

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

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

您可以切换到RIGHT JOIN,但如果您没有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)

COALESCE()是必要的,以便列始终返回TrnYear。