要查找重复的CTE?

时间:2018-09-18 15:26:29

标签: sql sql-server join common-table-expression

有人可以告诉我如何添加到此CTE中,以包括存储在另一个名为“ WeccoPartyAddress”的表中的“地址类型”列吗?

我正在尝试查找名字和姓氏以及邮寄地址(地址类型地址='邮寄'

)的重复项
with dups as (
 select 
      wp.GtId
 from CORE.WeccoParty wp
 where exists (select 1
              from CORE.WeccoParty wpe
              where wp.FirstName = wpe.FirstName
              and   wp.LastName  = wpe.LastName
              and   wp.Dob       = wpe.Dob
             and     wp.GtId     <> wpe.GtId
             ) 

  )
  select distinct
      wp.GtId, 
      wp.CrmPartyId, 
      wp.LegalName, 
      wp.BusinessClass, 
      wp.RmFullName, 
      wp.PbeFullName, 
      wp.OverallClientStatus, 
      wp.OverallRpStatus, 
      wp.FirstName + ' ' + wp.LastName FullName, 
      wp.Dob
   from CORE.WeccoParty wp
   join dups d on d.GtId = wp.GtId
   order by 9,1

1 个答案:

答案 0 :(得分:0)

请考虑通过在外部查询和子查询中向{em> WeccoPartyAddress 表添加所需的JOIN子句来扩展CTE。还要注意添加的WHERE以避免表之间可能存在的一对多关系的重复ID。

distinct

根据您知道的数据和关系(例如,GtId是否可以具有相同的生物详细信息和/或相同的邮寄地址?),您可能需要调整上述查询。这些可能涉及将with dups as ( select distinct p.GtId from CORE.WeccoParty p join CORE.WeccoPartyAddress a ON p.GtId = a.GtId where exists (select 1 from CORE.WeccoParty sub_p left join CORE.WeccoPartyAddress sub_a on sub_p.GtId = sub_a.GtId and sub_a.AddressType = 'Mailing' where (p.FirstName = sub_p.FirstName and p.LastName = sub_p.LastName and p.Dob = sub_p.Dob and p.GtId <> sub_p.GtId) and a.MailingAddress = sub_a.MailingAddress and a.GtId <> sub_a.GtId ) ) 交换为left join和/或join条件,例如:

WHERE