需要帮助T sql查询

时间:2013-01-05 12:53:32

标签: sql tsql sql-server-2008-r2

我有两张桌子。这些数据如下所示:

表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

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

2 个答案:

答案 0 :(得分: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 demo

答案 1 :(得分: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