簡體   English   中英

SQL Server計數重疊數(日期范圍)

[英]SQL Server Count number of overlaps (date ranges)

我有一張桌子,上面存放着車輛及其出租的日期。 我想找出日期重疊和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

您可以嘗試以下查詢:

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 

SQL提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM