无论连接语句

时间:2017-02-22 21:10:35

标签: join syntax sql-server-2012 full-outer-join

我很难找出正确构造此查询的正确语法。我试图显示SalesHistoryDe​​tail和SalesVsBudget表中的所有记录。我相信我的查询允许SalesVsBudget上的一些记录不被提取,而我想要在那段时间内全部记录,无论是否有相应的销售。这是我的代码:

SELECT  MAX(a.DispatchCenterOrderKey) AS DispatchCenter, 
        a.CustomerKey, 
CASE WHEN a.CustomerKey IN
             (SELECT AddressKey
              FROM FinancialData.dbo.DimAddress
              WHERE AddressKey >= 99000 AND AddressKey <= 99599) THEN 1 ELSE 0 END AS InterCompanyFlag, 
    MAX(a.Customer) AS Customer, 
        a.SalesmanID, 
    MAX(a.Salesman) AS Salesman, 
        a.SubCategoryKey, 
    MAX(a.SubCategoryDesc) AS Subcategory, 
    SUM(a.Value) AS SalesAmt, 
        b.FiscalYear AS Year, 
        b.FiscalWeekOfYear AS Week, 
    MAX(c.BudgetLbs) AS BudgetLbs, 
    MAX(c.BudgetDollars) AS BudgetDollars
FROM   dbo.SalesHistoryDetail AS a 
LEFT OUTER JOIN dbo.M_DateDim AS b ON a.InvoiceDate = b.Date 
FULL OUTER JOIN dbo.SalesVsBudget AS c ON a.SalesmanID = c.SalesRepKey 
                                  AND a.CustomerKey = c.CustomerKey 
                                  AND a.SubCategoryKey = c.SubCategoryKey 
                                  AND b.FiscalYear = c.Year AND b.FiscalWeekOfYear = c.WeekNo
GROUP BY a.SalesmanID, a.CustomerKey, a.SubCategoryKey, b.FiscalYear, b.FiscalWeekOfYear

我从中提取了两个不同的数据集,显然是SalesHistoryDe​​tail表和SalesVsBudget表。我希望从SalesVsBudget表中获取所有budgetLbs和BudgetDollars值,无论它们是否在连接中匹配。我也想要所有匹配的连接记录,但我也想要SalesVsBudget的每条记录。基本上我想显示所有销售记录,我想在销售员,客户,子类别,年份和周匹配时引用SalesVsBudget的预算值,但我还想查看属于我的日期范围的预算条目在此期间有相应的销售记录。希望这是有道理的。我觉得我非常接近,但我的预算数字并不反映整个故事,我认为这是因为我的一些记录被排除在外!请帮忙。

1 个答案:

答案 0 :(得分:0)

我能够通过玩FULL OUTER JOIN来实现这一目标。我的问题是SalesVsBudget中的记录多于SalesHistory_V。因此,我必须使SalesVsBudget初始FROM表和SaleHistory_V与FULL OUTER JOIN并排列所有记录。