sql

Prevent redundant results in SQL query


My query to find time clash works like this -

create table dat(id int, s time(7), e time(7));

insert into dat (id,s,e) values(1,'16:00:00.0000000','18:00:00.0000000')
insert into dat (id,s,e) values(2,'15:00:00.0000000','17:00:00.0000000')
insert into dat (id,s,e) values(3,'12:00:00.0000000','15:00:00.0000000')

//data part

QUERY - 

select * from dat a, dat b

 where  a.id != b.id 

and a.s < b.e and a.e > b.s

Result - enter image description here

Now the problem is that the query lists:

I need the distinct of this query.


Solution

  • Try:

    SELECT * from dat a, dat b 
    WHERE a.id < b.id 
        AND a.s < b.e 
        AND a.e > b.s
    

    You can avoid the duplicate pairs by setting first id to be lower than second id.