Assuming there is one row per person, this is a question of getting the overlap between two spans. The following query uses MySQL syntax to do this (MySQL supports least()
, greatest()
and limit
). This can be done in almost any database, but the exact syntax might vary:
select lt1.firstname, lt1.lastname, lt2.firstname, lt2.lastname,
greatest(0, datediff(least(lt1.EndDate, lt2.EndDate), greatest(lt1.StartDate, lt2.StartDate))) as overlap
from LongTable lt1 cross join
LongTable lt2
where lt1.id <> lt2.id
order by overlap desc
limit 1;
Here is a SQL Fiddle demonstrating it.