全外连接不能像我期望的那样工作

时间:2017-05-10 19:42:41

标签: sql sql-server-2012

select *
from [dbo].[Revenue_PL_S_F_M] rsfm
  full join [dbo].[Expense_Misc_Variable] emv 
    on emv.FISCYR = rsfm.FISCYR
    and emv.FISCPER = rsfm.FISCPER
    and emv.Warehouse = rsfm.Warehouse
    and emv.Customer = rsfm.Customer
where RSFM.FISCYR = 2017 
  and RSFM.FISCPER = 1 
  and RSFM.GLGroup = 'M'

emv中有3行,1没有匹配的rsfm.customer。此行未添加到视图中。

提前致谢 格里

2 个答案:

答案 0 :(得分:1)

您的where限制了您的加入。将where移至连接条件,或使用rsfm的派生表。

select *
from  [dbo].[Revenue_pl_S_F_M] rsfm
  full join [dbo].[Expense_Misc_Variable] emv
    on emv.fiscyr = rsfm.fiscyr
    and emv.fiscper = rsfm.fiscper
    and emv.Warehouse = rsfm.Warehouse
    and emv.Customer = rsfm.Customer
    and rsfm.fiscyr = 2017 
    and rsfm.fiscper = 1 
    and rsfm.glgroup = 'M'

select *
from  (
  select * 
  from [dbo].[Revenue_pl_S_F_M]  
  where fiscyr = 2017 
    and fiscper = 1 
    and glgroup = 'M'
    ) rsfm
  full join [dbo].[Expense_Misc_Variable] emv
    on emv.fiscyr = rsfm.fiscyr
    and emv.fiscper = rsfm.fiscper
    and emv.Warehouse = rsfm.Warehouse
    and emv.Customer = rsfm.Customer

答案 1 :(得分:0)

完全外部联接非常棘手,尤其是在过滤时。

我怀疑你可能想要:

select *
from [dbo].[Revenue_PL_S_F_M] rsfm full join
     [dbo].[Expense_Misc_Variable] emv 
      on emv.FISCYR = rsfm.FISCYR and
         emv.FISCPER = rsfm.FISCPER and
         emv.Warehouse = rsfm.Warehouse and
         emv.Customer = rsfm.Customer
where coalesce(RSFM.FISCYR, emv.FISCYR) = 2017 and
      coalesce(RSFM.FISCPER, emv.FISCPER) = 1 and
      coalesce(RSFM.GLGroup, emv.GLGroup) = 'M';

当表中的至少一个“匹配”行与您想要的条件匹配时,返回表之间的匹配。

我的猜测是,对于您遇到的任何问题,完全外部联接可能不是最好的方法。您可以考虑使用适当的数据样本和所需结果来提出另一个问题。