需要找到表之间的差异

时间:2017-02-22 12:52:32

标签: sql database rdbms

我的表结构如下: enter image description here

我需要找到表之间的差异,作为另一个表中不可用的数据(反之亦然)。 我能够找到差异如下:

enter image description here

使用了Sql Query:

select * 
from (select input_name_id, count(1) as cnt
      from Table1
      group by input_name_id
     ) a join 
     (select input_name_id, count(1) as cnt
      from Table2
      group by input_name_id
     ) b
     on (a.input_name_id = b.input_name_id)
where a.cnt <> b.cnt

预期结果:

enter image description here

我尝试了数字方式来提取数据,但我无法做到! 所以你的帮助非常感谢。谢谢

2 个答案:

答案 0 :(得分:1)

两件事:(1)全外连接; (2)枚举具有相同值的行:

select * 
from (select input_name_id, match_id, name, 
             row_number() over (partition by input_name_id, match_id, name order by name) as seqnum
      from Table1
     ) a full join 
     (select input_name_id, match_id, name, 
             row_number() over (partition by input_name_id, match_id, name order by name) as seqnum
      from Table2
     ) b
     on a.input_name_id = b.input_name_id and
        a.match_id = b.match_id and
        a.name = b.name and
        a.seqnum = b.seqnum
where a.seqnum is null or b.seqnum is null;

答案 1 :(得分:0)

使用结合所有

的简单解决方案
select null as a_input_name_id, null as a_matchid, null as a_name, input_name_id as b_input_name_id, matchid as b_matchid, name as b_name
from
(select input_name_id, matchid, name, row_number() over (partition by input_name_id, matchid, name order by input_name_id) as rw_num
from t2
except
select input_name_id, matchid, name, row_number() over (partition by input_name_id, matchid, name order by input_name_id) as rw_num
from t1 ) a


union all

select input_name_id as a_input_name_id, matchid as a_matchid, name as a_name, null as b_input_name_id, null as b_matchid, null as b_name
from
(select input_name_id, matchid, name, row_number() over (partition by input_name_id, matchid, name order by input_name_id) as rw_num
from t1
except
select input_name_id, matchid, name, row_number() over (partition by input_name_id, matchid, name order by input_name_id) as rw_num
from t2) b

enter image description here