我有一张桌子可以存放车辆和他们出租的日期。我想知道SQL Server 2008中的日期是否重叠以及车辆的重叠次数。我期望的结果如下。
ID Vehicle StartDate EndDate Overlap
==============================================================
1 Ford Focus 01/01/2014 31/01/2014 1
2 Ford Focus 20/01/2014 20/02/2014 1
3 Ford Focus 01/03/2014 28/03/2014 0
4 Mercedes 18/03/2014 24/03/2014 0
5 Mercedes 01/07/2014 31/07/2014 2
6 Mercedes 15/07/2014 31/07/2014 2
7 Mercedes 25/07/2014 25/08/2014 2
答案 0 :(得分:1)
您可以尝试此查询:
select *, (select count(*) from test
where not (v.StartDate > EndDate or v.EndDate < StartDate)
and Vehicle = v.Vehicle and ID != v.ID) as Overlap
from test v