Phi*_*lip 0 sql t-sql sql-server
我有以下查询,这些查询返回开始日期或结束日期在指定的日期范围之间的记录。
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)
Run Code Online (Sandbox Code Playgroud)
我的问题是开始日期为'2019年3月1日',结束日期为'2019年8月4日',这意味着它在2019年4月1日至2019年5月1日的日期范围内,但我的标准不满足那。
我如何包括这些类型的记录?
样本数据:
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
Run Code Online (Sandbox Code Playgroud)
我的情况如下:
(StartDate <= @ReportEndDate AND EndDate >= @ReportStartDate)
OR EndDate is null
Run Code Online (Sandbox Code Playgroud)
这实际上将检查日期范围是否重叠,这似乎正是您所要的。
ID | 开始日期| 结束日期 -:| :------------------ | :------------------ 1 | 01/03/2019 00:00:00 | 空值 2 | 01/03/2019 00:00:00 | 04/08/2019 00:00:00 3 | 14/07/2019 00:00:00 | 空值