I have a long table with following columns:

Id(Serial), FirstName(varchar15), LastName(varchar15), StartDate(date), EndDate(date)

and the entries are like:

* 1, Amar, XoXo, 2009-07-01, 2014-05-23.
* 2, Madhujita, Mami, 2009-03-11, 2014-06-24.
* 3, Akbak Ladar, 2000-04-12, 2009-01-01.
* 4, Abhashuk, Genjin, 2005-06-03, 2005-09-09.
* 5, Sinra, Iao, 2014-01-01, 2014-04-06

and so on till 500 members.

How can I find out which two people have spent most time together and how many days? Like for the given data Amar and Madhujita have spent the maximum time. Can this be done in a single query? Thank You.

有帮助吗?

解决方案

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.

其他提示

Thanx Gordon, I followed your trail and landed up with a query myself with better understanding

select x.firstname as firstname1,x.lastname as surname1,y.firstname as firstname2,y.lastname as surname2
            from staff x inner join staff y on 
            x.startDate <= y.endDate and y.startDate <= x.endDate and x.firstname!=y.firstname and x.surname!=y.surname HAVING MIN(ABS(DATEDIFF(x.startdate,x.endDate)-DATEDIFF(y.startDate,y.endDate)))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top