• First we need to full join the tables @b-2 and @C based on the code and the position of the bname and cname. Then later make right join with @a table.

    select a1.code,a1.aname,b1.bname,c1.cname

    from @C c1

    full join @b-2 b1

    on c1.code=b1.code and

    (select count(c2.code) from @C c2 where c1.cname>=c2.cname and c1.code=c2.code)

    =

    (select count(b2.code) from @b-2 b2 where b1.bname>=b2.bname and b1.code=b2.code)

    right join @a a1 on isnull(b1.code,c1.code)= a1.code