declare @table1 table(a varchar(10),val varchar(10))
insert into @table1 select 'A','A1'
insert into @table1 select 'A','A2'
insert into @table1 select 'A','A3'
insert into @table1 select 'A','A4'
insert into @table1 select 'A','A5'
insert into @table1 select 'B','B1'
insert into @table1 select 'B','B2'
insert into @table1 select 'B','B3'
insert into @table1 select 'B','B4'
insert into @table1 select 'B','B5'
insert into @table1 select 'B','B6'
insert into @table1 select 'C','C1'
insert into @table1 select 'C','C2'
insert into @table1 select 'D','D1'
insert into @table1 select 'D','D2'
insert into @table1 select 'D','D3'
insert into @table1 select 'D','D4'declare @table2 table(a varchar(10),val varchar(10))
insert into @table2 select 'A','X1'
insert into @table2 select 'A','X2'
insert into @table2 select 'B','Y1'
insert into @table2 select 'B','Y2'
insert into @table2 select 'B','Y3'
insert into @table2 select 'B','Y4'
insert into @table2 select 'B','Y5'
insert into @table2 select 'C','Z1'
insert into @table2 select 'C','Z2'
insert into @table2 select 'C','Z3'
insert into @table2 select 'C','Z4'
insert into @table2 select 'D','S1'
insert into @table2 select 'D','S2'select isnull(a.a,b.a)a,isnull(a.val,b.val)val,
val=case isnull(a.val,'') when '' then '' else isnull(b.val,'') end from 
@table1 a full join
@table2 b on a.a=b.a
and right(a.val,1)=right(b.val,1)
order by a,val