처음에는 단순하게 end_date에 있는 것이 start_date에 있으면 하나로 합치려고 join을 이용하여 다음과 같이 쿼리를 작성하였다.
select t3.start_date, t3.end_date
from (select
t1.start_date,
if(datediff(t2.end_date, t1.start_date) is null,
t1.end_date, t2.end_date) as end_date,
datediff(t2.end_date, t1.start_date) as dif
from projects as t1
left join (select start_date, end_date from projects) as t2
on t1.end_date = t2.start_date) as t3
order by t3.dif, t3.start_date desc
위 쿼리의 문제점은 다음과 같다.
따라서 start_date와 end_date가 서로 중복되지 않는 것들에 대하여 서로 묶어주고, 문제의 조건에 따라 다음과 같이 작성하였다.
select start_date, min(end_date)
from (select start_date
from projects
where start_date not in (select end_date from projects)) as a,
(select end_date
from projects
where end_date not in (select start_date from projects)) as b
where start_date < end_date
group by start_date
order by datediff(min(end_date), start_date), start_date