返回具有重叠日期的行

时间:2016-08-30 16:29:49

标签: sql date

我试图找到那些与其他行重叠日期的行。

示例数据:

Period: 13, Start Date: 9/1/2015, End Date: 9/30/2015

Period: 14, Start Date: 9/15/2015, End Date: 10/30/2015

Period: 15, Start Date: 11/1/2015, End Date: 11/30/2015

这是我当前的查询:

select pd1.periodNumber AS 'Period Seq A', pd1.startDate, pd1.endDate,   
pd2.periodNumber AS 'Period Seq B', pd2.startDate, pd2.endDate,    
pd2.adjustment 
from dbo.PeriodDefinition pd1 
inner join dbo.PeriodDefinition pd2 on pd2.startDate > pd1.startDate and   
pd2.startDate < pd2.endDate 
where (pd1.adjustment =1 AND pd2.adjustment = 1)

它应该只返回1行,并显示第13期(期间A)和期间14(期间B)的数据。现在它返回3行,并在结果中显示13和15。我错过了什么?谢谢!

1 个答案:

答案 0 :(得分:1)

and  pd2.startDate < pd2.endDate

应该是

and pd2.startDate < pd1.endDate  

我会写

on pd2.startDate between pd1.startDate and pd1.endDate

你也可能想要一个

and pd1.periodNumber != pd2.periodNumber

(假设periodNumber是唯一的行标识符。)