请教一个组合查询的问题
有两个表
表A
id enName
1 abcde fighi
2 zzzzz ddd
3 xxxxx yyyyyyy
表B(可能有同名不同组的记录)
enName cnName group
abcde fighi 用户一 g1
abcde fighi 用户一 g2
zzzzz ddd 用户二 g1
想要的结果,B中如果有则取cnName,否则取enName
id Name
1 测试一
2 用户二
3 xxxxx yyyyyyy
[解决办法]
- SQL code
create table #a(id int identity(1,1) primary key,enName varchar(30))insert into #aselect 'abcde fighi' union select 'zzzzz ddd' unionselect 'xxxxx yyyyyyy'create table #b(enName varchar(30),cnName varchar(30),grop varchar(10))insert #b select 'abcde fighi','用户一','g1' unionselect 'abcde fighi','用户一','g2' unionselect 'zzzzz ddd','用户二','g1'select distinct a.id,b.cnName as Namefrom #a ajoin #b b on a.enName=b.enNameunionselect id,enName as Namefrom #a where enName not in(select enName from #b)order by idid Name----------- ------------------------------1 用户一2 xxxxx yyyyyyy3 用户二(3 行受影响)