【问题标题】:Between date condition is not working in SQL Server日期之间的条件在 SQL Server 中不起作用
【发布时间】:2018-04-13 05:38:03
【问题描述】:

我有如下数据,

尝试在查询下方运行但返回 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 比突出显示的行中的范围早 1 天,2018-04-11 比突出显示的行晚 1 天。因此,没有一个语句是正确的,因此整个 where 语句对于突出显示的行返回 false。为了更好地解释,第一个 BETWEEN 转换为:ScheduleStartDate <= 2018-04-05 <= ScheduleEndDate 这是不正确的。第二个BETWEEN 声明也是如此。

标签: sql sql-server tsql date compare


【解决方案1】:

你可以重写为:

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

【讨论】:

  • 工作得很好;)
【解决方案2】:

这是因为

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

【讨论】:

  • 也许 Yogesh Sharma 的回答可以满足您的需求。
  • 我还添加了一个变体。也检查一下。
  • 从 Yogesh Sharma 的回答中得到了解决方案。你的回答也有效。谢谢
【解决方案3】:

你可以试试这个

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

【讨论】:

  • 这是一种替代方法,但不是答案
  • 工作得很好;)
【解决方案4】:

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

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

根据您的逻辑,您可能需要&lt;&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2021-08-18
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多