Reputation: 2628
I have the following query that returns records where the Start Date or End Date is between the date range specified.
DECLARE @ReportStartDate date = '01 Apr 2019'
DECLARE @ReportEndDate date = '01 May 2019'
select * from #temp
where
(StartDate between @ReportStartDate and @ReportEndDate) or
(EndDate between @ReportStartDate and @ReportEndDate) or
(EndDate is null)
The problem I have is where the Start Date is '01 Mar 2019' and the End Date is '04 Aug 2019', which means it was within the date range of 01 Apr 2019 and 01 May 2019, but my criteria doesn't meet that.
How could I include those type of records?
Sample data:
CREATE TABLE #temp
(
ID int,
StartDate datetime,
EndDate datetime NULL
)
insert into #temp
(
ID,
StartDate,
EndDate
)
select
1,
'01 Mar 2019',
NULL
union all
select
2,
'01 Mar 2019',
'04 Aug 2019'
union all
select
3,
'14 Jul 2019',
NULL
Upvotes: 0
Views: 1243
Reputation: 222682
I would phrase your condition as follows:
(StartDate <= @ReportEndDate AND EndDate >= @ReportStartDate)
OR EndDate is null
This will actually check if the date ranges do overlap, which seems to be what you are looking for.
ID | StartDate | EndDate -: | :------------------ | :------------------ 1 | 01/03/2019 00:00:00 | null 2 | 01/03/2019 00:00:00 | 04/08/2019 00:00:00 3 | 14/07/2019 00:00:00 | null
Upvotes: 5