日期间条件在SQL Server中不起作用

日期间条件在SQL Server中不起作用,sql,sql-server,tsql,date,compare,Sql,Sql Server,Tsql,Date,Compare,我有一个数据如下: 正在尝试运行下面的查询,但返回0行, 下面的查询应该返回高亮显示的行数据,如上所示 谁能解释一下,我错过了什么 select * from Flt_OperativeFlight_SchedulePeriods where ( (cast('2018-04-05' as date) between cast(ScheduleStartDate as date) and cast(ScheduleEndDate as date) ) or (c

我有一个数据如下:

正在尝试运行下面的查询,但返回0行, 下面的查询应该返回高亮显示的行数据,如上所示

谁能解释一下,我错过了什么

select * from Flt_OperativeFlight_SchedulePeriods
where  
(
    (cast('2018-04-05' as date) between cast(ScheduleStartDate as date) and   cast(ScheduleEndDate as date) )
    or
    (cast('2018-04-11' as date) between cast(ScheduleStartDate as date) and   cast(ScheduleEndDate as date) )
) 
and CarrierCode='SQ' and FlightNumber='0004'
因为

'2018-04-05' < '2018-04-06'
and
'2018-04-11' > '2018-04-10'
您可以重新编写为:

选择*
从航班时刻表开始
其中CarrierCode='SQ'和FlightNumber='0004'和
(ScheduleStartDate>='2018-04-05'和ScheduleEndDate您可以试试这个

SELECT * 
FROM `Flt_OperativeFlight_SchedulePeriods` 
WHERE ScheduleStartDate >= '2018-04-05' AND ScheduleEndDate <= '2018-04-11' 
      AND CarrierCode='SQ' and FlightNumber='0004'
选择*
从“航班时刻表时段”开始

如果ScheduleStartDate>='2018-04-05'和ScheduleEndDate似乎希望获得重叠的时段,则需要以下逻辑:

start_1 <= end_2 and end_1 >= start_2
start_1=start_2
对于您的查询:

where  
(
    cast('2018-04-05' as date) <= cast(ScheduleEndDate as date) 
    and
    cast('2018-04-11' as date) >= cast(ScheduleStartDate as date)
) 
在哪里
(
cast(“2018-04-05”截止日期)=cast(附表STARTDATE截止日期)
) 

根据您的逻辑,您可能必须

您的
2018-04-05
在突出显示行中的范围前1天,而
2018-04-11
在突出显示行中的范围后1天。因此,没有一条语句是真的,因此整个where语句对于突出显示行返回false。为了更好地解释,第一条
BETWEEN
翻译成:
ScheduleStartDate也许Yogesh Sharma的答案符合你的要求。我还添加了一个变体。也检查一下。从Yogesh Sharma的答案中得到了解决方案。你的答案也很有效。谢谢。这是一种替代方法,但不是一个答案。工作非常好;)工作非常好;)
start_1 <= end_2 and end_1 >= start_2
where  
(
    cast('2018-04-05' as date) <= cast(ScheduleEndDate as date) 
    and
    cast('2018-04-11' as date) >= cast(ScheduleStartDate as date)
)