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

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

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

  1. id sdate edate tag
  2. S1 20180610 20180611 0
  3. S2 20180610 20180612 0
  4. S3 20180612 20180613 0
  5. S5 20180612 20180613 1

表B

  1. id sdate edate tag
  2. S1 20180610 20180611 0
  3. S2 20180611 20180612 0
  4. S3 20180612 20180613 1
  5. S4 20180612 20180613 1

所需输出

  1. S3 20180612 20180613 0
  2. S5 20180612 20180613 1
  3. S4 20180612 20180613 1

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

euoag5mw

euoag5mw1#

  1. select * from (select * from tableA
  2. union DISTINCT
  3. select * from tableB) as finalTable
  4. where id not in (select * from tableA t1 join tableB t2
  5. 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将出现两次,因为在这两种情况下标志值是不同的。
您可以根据需要修改以下查询并获得结果。因为我们只连接这些表一次,所以它的性能比连接两次要好得多。

  1. select distinct
  2. case when a.id is not null then a.id else b.id end as id,
  3. case when a.sdate is not null then a.sdate else b.sdate end as sdate,
  4. case when a.edate is not null then a.edate else b.edate end as edate,
  5. case when a.tag is not null then a.tag else b.tag end as tag,
  6. case when a.id is not null then 'table1' else 'table2' end as tb_id
  7. from table1 a
  8. full join table2 b
  9. on a.id=b.id
  10. and a.sdate=b.sdate
  11. and a.edate=b.edate
  12. and a.tag=b.tag
  13. where (a.id is null
  14. and a.sdate is null
  15. and a.edate is null
  16. and a.tag is null)
  17. or (b.id is null
  18. and b.sdate is null
  19. and b.edate is null
  20. and b.tag is null)
展开查看全部
dhxwm5r4

dhxwm5r43#

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

  1. create table unmatched as
  2. select
  3. a.*
  4. from tableA as a left join (select *, true as flag from tableB) as b on
  5. a.id=b.id a.sdate=b.sdate a.edate=b.edate a.tag=b.tag
  6. where b.flag is null --this will get records in tableA but not in table B
  7. union all
  8. select
  9. b.*
  10. from tableB as b left join (select *, true as flag from tableA) as a on
  11. a.id=b.id a.sdate=b.sdate a.edate=b.edate a.tag=b.tag
  12. where a.flag is null --this will get records in tableB but not in table A
  13. ;

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

相关问题