简体   繁体   中英

How to return records between a Start Date and End Date

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

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.

Demo on DB Fiddle :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM