Skip to content
Advertisement

Eliminate the rows that becomes same after swapping as in original table in SQL Server

I have a table which contains data as follows:

create table journey(
Src varchar(255), Dest varchar(255))

insert into journey values('Jaipur', 'Mumbai'), ('Mumbai', 'Jaipur'), ('Kolkata', 'Bangalore'), ('Bangalore', 'Indore'), ('Indore', 'Lucknow'), ('Lucknow', 'Indore')

I want a table which do not have Mumbai—>Jaipur as it is present already before being swapped. Similarly, Lucknow—>Indore is not required. All other entries must come as it is which is there in the existing table.

Can any body help.

Note: Table must not have any id or S.No. in the table.

Advertisement

Answer

You can create a view or use select statement with not exists to prevent duplicate journey :

select j.*
from journey  j
where not exists (select 1 
                  from journey j1 
                  where j1.src = j.dest and j1.dest = j.src and 
                        j1.src < j.src and j1.dest > j.dest
                 );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement