有这样的两个表:
Table A:
name Dept age
----------------
mary IT 23
henry fs 25
joyce pr 28
Table B:
name Dept Sex
----------------
mary HR F
henry fs m
joyce ps F
我现在想要把这两个表比较,
得出不同记录,并放在一起比较,
并能多出一个字段Remark做判断是否相同。
得出结果如下:
name Dept_A Dept_B age sex Remark
-------------------------------------
mary IT HR 23 f N
henry fs fs 25 m Y
joyce pr ps 28 f N
解决方案
declare @A table(name varchar(10),Dept varchar(10),age int)
insert into @A select 'mary ','IT',23
insert into @A select 'henry','fs',25
insert into @A select 'joyce','pr',28
declare @B table(name varchar(10),Dept varchar(10),sex char(1))
insert into @B select 'mary ','HR','F'
insert into @B select 'henry','fs','m'
insert into @B select 'joyce','ps','F'
select
A.name,A.Dept as Dept_A,B.Dept as Dept_B,A.age,B.Sex,
(case when A.Dept=B.Dept then 'Y' else 'N' end) as Remark
from
@A A,@B B
where
A.name=B.name