配置单元外部表-选择不匹配的记录

gt0wga4j  于 2021-06-26  发布在  Hive
关注(0)|答案(3)|浏览(262)

我已经创建了两个配置单元外部表(sql查询将起作用),它们指向我需要比较两个输出的位置。
我需要比较两个表并选择不匹配的记录。

id   sdate   edate  tag

S1 20180610 20180611 0

S2 20180610 20180612 0

S3 20180612 20180613 0

S5 20180612 20180613 1

表B

id  sdate    edate  tag

S1 20180610 20180611 0

S2 20180611 20180612 0

S3 20180612 20180613 1

S4 20180612 20180613 1

所需输出

S3 20180612 20180613 0

S5 20180612 20180613 1

S4 20180612 20180613 1

试图通过连接两个表来编写查询,但对我无效。
谢谢你的帮助
谢谢:)

euoag5mw

euoag5mw1#

select * from (select * from tableA
union DISTINCT  
select * from tableB) as finalTable
where id not in (select * from tableA t1 join tableB t2
              on t1.is=t2.id and t1.sdate=t2.sdate and t1.edate=t2.edate and t1.tag=t2.tag);

第一个union distinct行并使finaltable。它有所有独特的行。
然后在两个表之间进行内部连接。
最后减去它们,现在你得到答案了。
exmaple公司:

如果你把一秒减去一秒,那么你就得到了你想要的[1,4]

zujrkrfu

zujrkrfu2#

我们可以使用下面的查询轻松地做到这一点。
请注意,我不知道为什么要从输出中删除s2,因为这在两个表中是明显不同的。
另外,如果您想在两个表中找到不同的记录,那么s3将出现两次,因为在这两种情况下标志值是不同的。
您可以根据需要修改以下查询并获得结果。因为我们只连接这些表一次,所以它的性能比连接两次要好得多。

select distinct
case when a.id is not null then a.id else b.id end as id,
case when a.sdate is not null then a.sdate else b.sdate end as sdate,
case when a.edate is not null then a.edate else b.edate end as edate,
case when a.tag is not null then a.tag else b.tag end as tag,
case when a.id is not null then 'table1' else 'table2'  end as tb_id
from table1 a
full join table2 b
on a.id=b.id 
and a.sdate=b.sdate 
and a.edate=b.edate 
and a.tag=b.tag
where (a.id is null
and a.sdate is null
and a.edate is null
and a.tag is null) 
or (b.id is null
and b.sdate is null
and b.edate is null
and b.tag is null)
dhxwm5r4

dhxwm5r43#

此查询将帮助您高效地识别记录

create table unmatched as 
select 
a.*
from tableA as a left join (select *, true as flag from tableB) as b on
a.id=b.id a.sdate=b.sdate a.edate=b.edate a.tag=b.tag
where b.flag is null --this will get records in tableA but not in table B
union all 
select 
b.*
from tableB as b left join (select *, true as flag from tableA) as a on
a.id=b.id a.sdate=b.sdate a.edate=b.edate a.tag=b.tag
where a.flag is null --this will get records in tableB but not in table A
;

您可以使用完全联接来执行此操作,但效率要低得多

相关问题