with Cr_a
as (select 1 客户号,'A' 等级,100 额度 union
select 2 客户号,'A' 等级,100 额度 union
select 3 客户号,'A' 等级,300 额度 ) ,
Cr_b
as (select 2 客户号,'2015' 年审年度,'A' 等级,'2015100' 额度 union
select 2 客户号,'2016' 年审年度,'A' 等级,'2016200' 额度 union
select 3 客户号,'2017' 年审年度,'A' 等级,'2017300' 额度)
select aa.客户号,case when bb.客户号 is null then aa.等级 else bb.等级 end 等级,case when bb.客户号 is null then aa.额度 else bb.额度 end 额度
from Cr_a aa left outer join (select b.*
from (select ROW_NUMBER() over(PARTITION BY 客户号 order by 年审年度) sn,* from Cr_b b ) b
where b.sn=1) bb on bb.客户号=aa.客户号
select a.等级,a.额度 from a left outer join b
on a.客户号=b.客户号 where b.客户号 is null
unin
select t.等级,t.额度
from a inner join
(select top 1 客户号,年审年度,等级,额度 from b
left outer join
(select top 1 客户号,年审年度,等级,额度
from b grop by 年审年度
hvaing(count(*)>1)
) a
on a.客户号=b.客户号 and a.年审年度<>b.年审年度) tmp t
on a.客户号=t.客户号
unin
select b.等级,b.额度 from a
inner join b
on a.客户号=b.客户号
group by b.客户号
having(count(*)=1)