在相应的表中查找缺失的记录

find missing records in corresponding tables

假设我有两个临时 table 数据看起来像这样...

 #Temp1
 Id   IDNo       CdId       ApptDate        Proc
 1    X111       PP         3/3/2020        N
 2    X222       ZZ         3/3/2020        N
 3    X333       HH         3/3/2020        Y


 #Temp2
 ID  IDNo      CdID        ApptDate        Proc
 1   X111      PP          3/3/2020        Y
 2   X222      ZZ          3/3/2020        N
 3   X333      HH          3/3/2020        Y
 4   X444      BB          3/5/2020        Y

这是我想要实现的目标

1) 排除#TEMP1 和#TEMP2 中在 IdNO、CdId、ApptDate、PROC=Y 上具有相同匹配的所有记录

我只对发现这些场景感兴趣:

1) 从#Temp1 或#Temp2 中查找与所有列(PROC 除外)匹配的记录。例如,#Temp1 在#Temp2 中有对应的记录。 #Temp1 有 PROC=N 而#Temp2 有 PROC=Y,所以在#TEMP1 中显示记录并添加一个列,如 DESC = 'TEMP1 record has Proc=N'

2) 如果#TEMP1 或#TEMP2 在table 中都没有相应的记录,则显示该记录为 DESC = 'TEMP1 没有此记录),反之亦然。

3) 如果两个 table 中都存在匹配记录,但两个记录都有 PROC=N,则显示两个记录消息 'Temp1 record has Proc=N' 和 'Temp2 record has Proc = N'

所有我希望达到的结果是这样的:

ID    IdNo           CdID          ApptDate        DESC
 1    X111           PP            3/3/2020        'TEMP1 has Proc = N'
 2    X222           ZZ            3/3/2020        'TEMP1 has PROC = N'
 3    X222           ZZ            3/3/2020        'TEMP2 has PROC = N'
 4    X444           BB            3/5/2020        'TEMP 1 Does not have matching record'

在上面的结果中

第 1 行:此记录存在于#Temp1 和#Temp2 但#Temp1 Proc = N

第 2,3 行:此记录存在于#Temp1 和#Temp2 但在这两种情况下 PROC = N

第 4 行:此记录存在于#Temp2 但不存在于#Temp1

嗯。 . .我认为你想要的逻辑使用 union all:

select t1.idno, t1.cdid, t1.apptdate,
       (case when t2.idno is not null then 'Temp1 has proc N'
             when t2.idno is null then 'Temp2 is missing' end)
from table1 t1 left join
     table2 t2
     on t1.idno = t2.idno and t1.cdid = t2.cdid and t1.apptdate = t2.appdate
where t1.proc = 'N'
union all
select t2.idno, t2.cdid, t2.apptdate,
       (case when t1.idno is not null then 'Temp2 has proc N'
             when t1.idno is null then 'Temp1 is missing' end)
from table1 t2 left join
     table2 t1
     on t1.idno = t2.idno and t1.cdid = t2.cdid and t1.apptdate = t2.appdate
where t2.proc = 'N';

你也可以使用JOIN,这里是demo。如果两个表中的记录都有 PROC = Y,我已经设置了条件 statement

select
    Id,
    IDNo,
    CdId,
    ApptDate,
    case 
        when (t1_proc = 'N' and t2_proc = 'Y') or (t1_proc = 'Y' and t2_proc = 'N')  then 'TEMP1 has Proc = N'
        when (t1_proc = 'N' and t2_proc = 'N')
        then 'Temp1 record has Proc=N and Temp2 record has Proc = N'
        when (t1_proc = 'Y' and t2_proc = 'Y')
        then 'Temp1 record has Proc=Y and Temp2 record has Proc = Y'
        else
        'TEMP 1 Does not have matching'
    end as desc     
from 
(
  select
      a.Id,
      a.IDNo,
      a.CdId,
      a.ApptDate,
      a.proc as t2_proc,
      b.proc as t1_proc
  from table2 a
  left join table1 b
  on a.id = b.id
  and a.IDNo = b.IDNo
  and a.CdId = b.CdId
  and a.ApptDate = b.ApptDate
) vals
order by
    Id