在日期之间无法在MS-SQL中工作

时间:2018-04-13 05:38:04

标签: sql sql-server date

我的数据如下,

Data

尝试在查询下运行但返回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'

4 个答案:

答案 0 :(得分:1)

这是因为

'2018-04-05' < '2018-04-06'
and
'2018-04-11' > '2018-04-10'

作为变体,也许这就是你想要的

select * 
from Flt_OperativeFlight_SchedulePeriods 
where CarrierCode='SQ' and FlightNumber='0004' and
      (
           (ScheduleStartDate between '20180405' and '20180411')
        or (ScheduleEndDate between '20180405' and '20180411')
      )

答案 1 :(得分:1)

你可以重写

select * 
from Flt_OperativeFlight_SchedulePeriods 
where CarrierCode='SQ' and FlightNumber='0004' and
      (ScheduleStartDate >= '2018-04-05' and ScheduleEndDate <= '2018-04-11')

答案 2 :(得分:1)

你可以试试这个

SELECT * 
FROM `Flt_OperativeFlight_SchedulePeriods` 
WHERE ScheduleStartDate >= '2018-04-05' AND ScheduleEndDate <= '2018-04-11' 
      AND CarrierCode='SQ' and FlightNumber='0004'

答案 3 :(得分:0)

好像你想要重叠期,那么你需要这个逻辑:

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)
) 

根据您的逻辑,您可能需要<>