比较 3 SQL 服务器 table,一旦根据某些属性匹配,将结果放在一个 table 上,当不匹配时,将结果放在另一个上

Compare 3 SQL Server tables and once matched based on some attribute put the result on one table when not matched put the result in another

我的要求很简单,有3个SQL服务器table是这样的:

我希望根据所有 table 中的姓名、出生日期、性别和邮政编码加入(内部加入),如果记录匹配,我想将结果放在一个 table 中剩下的记录我想放在另一个 table 中以供进一步 comparison/processing.

第一部分很简单,这个查询:

SELECT AID, BID, CID, A.Name, A.DOB, A.Gender, A.PostCode
FROM TAB_A
JOIN TAB_B B ON A.Name = B.Name 
             AND A.DOB = B.DOB 
             AND A.Gender = B.Gender 
             AND A.PostCode = B.PostCode
JOIN TAB_C C ON A.Name = C.Name 
             AND A.DOB = C.DOB 
             AND A.Gender = C.Gender 
             AND A.PostCode = C.PostCode

但是不匹配的剩余记录的第二部分需要将它们放在单独的 table.

例如,如果在所有 3 table 中共有 50 条记录(A = 20,B=20 和 C=10),并且根据上述查询,所有记录都匹配的输出是 5,我希望在单独的 table.

中存储 95 条记录

您的 help/answer 将不胜感激。

谢谢

您可以使用union all 来合并表格。然后使用 window 函数按您关心的列计算匹配项。

Return匹配小于3的行:

select id, Name, DOB, Gender, PostCode
from (select id, Name, DOB, Gender, PostCode,
count(*) over (partition by Name, DOB, Gender, PostCode) as cnt
      from ((select AID as id, Name, DOB, Gender, PostCode
             from a
            ) union all
            (select BID, Name, DOB, Gender, PostCode
             from b
            ) union all
            (select CID, Name, DOB, Gender, PostCode
             from c
            )
           ) abc
      ) abc
where cnt < 3;