繁体   English   中英

查找另一个供应商数据库中作为两个记录存在的一条记录

[英]Find one record that exists as two records in another vendor database

我有两个供应商数据库,在我试图纠正的这些年中,它们已经变得非常不同步。 一个客户可以有多个id_numbers ,并且两个供应商数据库中都存在这些ID。 单个客户的所有ID都正确地附加到Vendor1数据库中的一个客户记录(意味着它们属于相同的customer_code )。 但是,问题在于,这些相同的ID可能会在Vendor2数据库中的多个客户之间Vendor2 ,这是不正确的。 我将需要将这多个客户合并到Vendor2数据库中。

我正在尝试确定第二个供应商数据库中哪些客户被表示为两个或多个客户。 到目前为止,我已经将两者结合在一起,但是我无法弄清楚如何只为同一customer_code找到具有两个或更多不同MemberInternalKeyscustomer_code

这是我到目前为止的内容:

select top 10
    c.customer_code,
    i.id_number,
    cc.MemberInternalKey
from Vendor1.dbo.customer_info as c
join Vendor1.dbo.customer_ids as i
  on c.customer_code = i.customer_code
join Vendor2.dbo.Clubcard as cc
  on (i.id_number collate Latin1_General_CI_AS_KS) = cc.ClubCardId
where i.id_code = 'PS'

在下面的示例中,我希望仅返回表中的最后两行。 前两行不应包含在结果中,因为它们对于两个记录都具有相同的MemberInternalKey ,并且属于相同的customer_code 第三行也不应包括在内,因为两个供应商数据库之间存在1-1匹配。

customer_code | id_number | MemberInternalKey
--------------|-----------|------------------
5549032       | 4000      | 4926877
5549032       | 4001      | 4926877
5031101       | 4007      | 2379218
2831779       | 4029      | 1763760
2831779       | 4062      | 4950922

任何帮助是极大的赞赏。

如果我理解正确,则可以将窗口函数用于此逻辑:

select c.*
from (select c.customer_code, i.id_number, cc.MemberInternalKey,
             min(MemberInternalKey) over (partition by customer_code) as minmik,
             max(MemberInternalKey) over (partition by customer_code) as maxmik
      from Vendor1.dbo.customer_info c join
           Vendor1.dbo.customer_ids i
           on c.customer_code = i.customer_code join
           Vendor2.dbo.Clubcard as cc
           on (i.id_number collate Latin1_General_CI_AS_KS) = cc.ClubCardId
      where i.id_code = 'PS'
     ) c
where minmik <> maxmik;

这将为每个customer_code计算最小和最大MemberInternalKey 然后,外部where仅返回这些位置不同的行。

另一种选择是

Declare @YourTable table (customer_code int, id_number int, MemberInternalKey int)
Insert Into @YourTable values
(5549032,4000,4926877),
(5549032,4001,4926877),
(5031101,4007,2379218),
(2831779,4029,1763760),
(2831779,4062,4950922)

Select A.*
 From  @YourTable A
 Join (
        Select customer_code
         From  @YourTable
         Group By customer_code
         Having min(MemberInternalKey)<>max(MemberInternalKey)
      ) B on A.customer_code=B.customer_code

退货

customer_code   id_number   MemberInternalKey
2831779         4029        1763760
2831779         4062        4950922

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM