MSSQL 比较 2 列问题

MSSQL comparing 2 columns issue

我有两个 table: 客户信息,如 id、customerName、地址等。和 RecipientOfGoods - customerId、地址。 两个 table 的地址不同,客户 table 中的地址是注册地址,第二个 table 中的地址是送货地址。我需要在第一个 table 添加收件人地址,以便比较两种地址。

use dwh01
SELECT distinct
       cus.[BranchId]
      ,cus.[CustomerId]
      ,cus.[CustomerName]
      ,cus.[Street] as StreetByReg
      ,del.Street as StreetForDelivery
      ,cus.[Postalcode] as PKByReg
      ,del.Postalcode as PKForDelivery
      ,cus.[City] as CityByReg
      ,del.City as CityForDelivery
      ,cus.[PhoneNumber]
      ,cus.[EMail]
      ,cus.[IsActive]
      ,cus.[LastChangeDate]
  FROM [dwh01].[live].[DimCustomer] cus 
 join live.DimRecipientOfGoods del on del.RecipientOfGoodsid = cus.Customerid
 where cus.BranchId in('1080','1081') and ltrim(cus.CustomerId) = '99060' 

这就是我的查询,我确实得到了所需的结果,但我也在第二行获得了相同的信息,但在第二行的地址列中 table 我从第一行获得了地址 table.问题是如何删除出现的无用的第二行以及为什么会这样?

请使用左联接代替内部联接从 DimCustomer 获取所有客户信息,但仅从 DimRecipientOfGoods 获取附加地址信息。

因为第二个 table 中有两个单独的地址信息,一个与第一个 table 完全匹配。您可以从第一个 table 和 在第二个 table 中,您可以通过比较两个地址来忽略该地址。但我不确定这种情况是否对所有客户都是一样的。如果你想删除那些有 DimRecipientOfGoods 中没有记录 table。

 use dwh01
    SELECT Distinct
           cus.[BranchId]
          ,cus.[CustomerId]
          ,cus.[CustomerName]
          ,cus.[Street] as StreetByReg
          ,del.Street as StreetForDelivery
          ,cus.[Postalcode] as PKByReg
          ,del.Postalcode as PKForDelivery
          ,cus.[City] as CityByReg
          ,del.City as CityForDelivery
          ,cus.[PhoneNumber]
          ,cus.[EMail]
          ,cus.[IsActive]
          ,cus.[LastChangeDate]
      FROM [dwh01].[live].[DimCustomer] cus 
     Left join live.DimRecipientOfGoods del on del.RecipientOfGoodsid = cus.Customerid
 AND (cus.Street <> del.Street OR cus.Postalcode <> del.Postalcode OR cus.City <> del.City) 
     where cus.BranchId in('1080','1081') and ltrim(cus.CustomerId) = '99060' 

JOIN 排除相等的行以仅获取具有新地址的客户。

SELECT distinct
       cus.[BranchId]
      ,cus.[CustomerId]
      ,cus.[CustomerName]
      ,cus.[Street] as StreetByReg
      ,del.Street as StreetForDelivery
      ,cus.[Postalcode] as PKByReg
      ,del.Postalcode as PKForDelivery
      ,cus.[City] as CityByReg
      ,del.City as CityForDelivery
      ,cus.[PhoneNumber]
      ,cus.[EMail]
      ,cus.[IsActive]
      ,cus.[LastChangeDate]
  FROM [dwh01].[live].[DimCustomer] cus 
  JOIN live.DimRecipientOfGoods del ON del.RecipientOfGoodsid = cus.Customerid 
     AND (cus.[Street] <> del.[Street] OR cus.[Postalcode] <> del.[Postalcode] OR cus.[City] <> del.[City]) 
  WHERE cus.BranchId in('1080','1081') and ltrim(cus.CustomerId) = '99060'