协助复制查询

时间:2015-03-26 23:02:27

标签: tsql ssrs-2008-r2

当新客户与我们联系时,会为他们分配一个参考编号。

不幸的是,我们的联络中心有时会记录同一个人,而不会检查他们之前是否与我们联系,并且客户最终会得到两个参考号码。我们想要清理它,所以:

如果客户的参考号不同,我想输出客户的姓氏,地址1和邮政编码重复但仅的实例。

这是我希望看到输出的数据类型:

参考姓氏地址1邮编   1875 Faulkner 10 Smith Street 08540   1876年福克纳10史密斯街08540

我尝试了一些想法,最新的想法(原谅大量的代码):

with Duplicates as
(
    select r.LastName
     , a.Address1
     , a.ZipCode
     , COUNT(*) as DuplicateCount
    FROM Reference r
    INNER JOIN Address a ON a.ReferenceNumber = r.ReferenceNumber 
    LEFT OUTER JOIN Telephone t ON r.ReferenceNumber = t.ReferenceNumber
    LEFT OUTER Join Email e ON r.ReferenceNumber = e.ReferenceNumber
    group by r.LastName
    , a.Address1
    , a.ZipCode
   having COUNT(*) > 1

SELECT
    r.ReferenceNumber
   , r.LastName
   , r.FirstName
   ,a.ReferenceNumber 
   , a.Address1
   , a.Address2
   , a.Address3
   , a.Address4
   , a.ZipCode
   ,t.ReferenceNumber
   , t.TelephoneNumber
  ,e.ReferenceNumber
  , e.EmailAddress
  , d.DuplicateCount
FROM Reference r
INNER JOIN Address a ON a.ReferenceNumber = r.ReferenceNumber 
LEFT OUTER JOIN Telephone t ON r.ReferenceNumber = t.ReferenceNumber
LEFT OUTER Join Email e ON r.ReferenceNumber = e.ReferenceNumber
join Duplicates d on d.LastName = r.LastName
                AND d.Address1 = a.Address1
                AND d.ZipCode = a.ZipCode;

不幸的是,这会返回所有重复项,而不是具有相同姓氏,地址1和邮政编码以及不同参考编号的重复项。 您对如何实现这一目标有什么建议吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

通过将数据放入表变量或使用别名,尝试在自联接中使用此部分代码。

SELECT
r.ReferenceNumber
, r.LastName
, r.FirstName
,a.ReferenceNumber 
, a.Address1
, a.Address2
, a.Address3
, a.Address4
, a.ZipCode
,t.ReferenceNumber
, t.TelephoneNumber
,e.ReferenceNumber
, e.EmailAddress
, d.DuplicateCount
FROM Reference r
INNER JOIN Address a ON a.ReferenceNumber = r.ReferenceNumber 
LEFT OUTER JOIN Telephone t ON r.ReferenceNumber = t.ReferenceNumber
LEFT OUTER Join Email e ON r.ReferenceNumber = e.ReferenceNumber

自我加入的一个例子是here