3

我有两张桌子。其中的数据如下所示:

表格1:

Col1      Col2
----------------
A          A1
A          A2
A          A3
B          B1
B          B2
B          B3

表 2:

Col1        Col2
------------------
A            A1
A            A4
A            A5
B            B1
B            B4
B            B5

我需要根据 Col1 中的值找出两个表的 Col2 中的数据差异。输出应如下所示:

输出:

Col    MismatchValuesInTable1     Mismatchvaluesintable2
---------------------------------------------------------
A               A2                       A4
                A3                       A5
B               B2                       B4
                B3                       B5

请帮我查询以实现上述目标。

4

2 回答 2

5
select isnull(t1.Col1,t2.Col2) as Col,
  t1.Col2 as MismatchValuesInTable1, 
  t2.Col2 as MismatchValuesInTable2

from t1
FULL JOIN t2 on (t1.Col1=T2.Col1) and (t1.Col2=t2.Col2)
where t1.Col2 is null or t2.Col2 is null
order by Col

SQLFiddle 演示

于 2013-01-05T13:04:53.427 回答
0

这将生成您拥有的输出表。不确定职位是否对您的问题很重要?如果是这样,则基于表 T1 中 A 的第二个值与表 T2 中 A 的第二个值不匹配这一事实匹配。

create table T1
(col1 varchar(10),
col2 varchar(10))

create table T2
(col1 varchar(10),
col2 varchar(10))


insert into T1
select 'A','A1'
union all
select 'A','A2'
union all
select 'A','A3'
union all
select 'B','B1'
union all
select 'B','B2'
union all
select 'B','B3'

insert into T2
select 'A','A1'
union all
select 'A','A4'
union all
select 'A','A5'
union all
select 'B','B1'
union all
select 'B','B4'
union all
select 'B','B5'

select T1.col1, T1.col2, T2.col2
from (select row_number() over(partition by Col1 order by Col1, Col2) as row_number, 
* from T1) as T1
inner join 
(select row_number() over(partition by Col1 order by Col1, Col2) as row_number, 
* from B) as T2
on T1.col1 = T2.col1
and T1.row_number = T2.row_number
where T1.col2 <> T2.col2
于 2013-01-05T16:30:09.073 回答