Q&A for anime and manga fans
declare @t table ( orderId int, code_dest char(1) ) declare @t2 table ( ID_VOIT int, orderId int, code_dest char(1) ) declare @t3 table ( voit_id int, code_dest char(1) ) insert into @t values (1, 'a') insert into @t values (2, 'b') insert into @t values (3, 'c') insert into @t values (4, 'a') insert into @t values (5, 'a') insert into @t values (6, 'b') insert into @t values (7, 'g') insert into @t3 values (1, 'a') insert into @t3 values (2, 'b') insert into @t3 values (3, 'c') insert into @t3 values (4, 'g') insert into @t2 select voit_id, orderId, t.code_dest from @t t join @t3 t3 on t.code_dest = t3.code_dest order by code_dest, orderId select * from @t2