查找对应表中缺失的记录
Posted
技术标签:
【中文标题】查找对应表中缺失的记录【英文标题】:find missing records in corresponding tables 【发布时间】:2020-04-27 00:54:02 【问题描述】:假设我有两个临时表,其中的数据看起来像这样......
#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 在任一表中都没有对应的记录,则将该记录显示为DESC = 'TEMP1 没有此记录),反之亦然。
3) 如果两个表中都存在匹配的记录,但两条记录的 PROC=N,则显示两条记录,并显示消息“Temp1 记录具有 Proc=N”和“Temp2 记录具有 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 中
【问题讨论】:
【参考方案1】:嗯。 . .我认为您想要的逻辑使用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';
【讨论】:
嗨,戈登,一如既往地谢谢你。您的答案几乎解决了所有问题,除了 #Temp1 或 #Temp2 中可能存在但在另一个表中没有相应记录的任何记录。 @Koosh 。 . .case
和 left join
应该处理这个问题。
谢谢我的错误,我在查询中添加错误【参考方案2】:
你也可以使用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
【讨论】:
这里的问题是您正在执行 LEFT JOIN。 TEMP1 有记录而 TEMP2 没有记录(基本上相反的情况)。我想知道 FULL JOIN 是否会解决这个问题 如果您查看#TEMP2 表,它的记录ID=X444 并且在#TEMP1 中没有对应的记录。但可能存在#TEMP1中的记录在#TEMP2中没有对应记录的情况。 如果您想要所有记录,@Koosh 然后union all
是最佳选择。您也可以使用full join
,但不会建议。以上是关于查找对应表中缺失的记录的主要内容,如果未能解决你的问题,请参考以下文章