【问题标题】:I am getting data between a start time and an end time, but what if the end time is null?我在开始时间和结束时间之间获取数据,但如果结束时间为空怎么办?
【发布时间】:2019-10-17 15:45:34
【问题描述】:

我有一个停车场数据库。我编写了一个存储过程来获取给定特定日期时间的所有空白点。我的查询如下:

 select Count(ParkingSlotId) as 'Empty Spots'
   from [ParkingLot].[ParkingSlot]
  where ParkingSlotId not in
       (select ParkingSlotId
          from [Transaction].[ParkingTransaction]
         where @searchTime between TimeIn and [TimeOut]) 

此查询工作正常,除非 TimeOut 为空,这意味着此人尚未离开。如果 TimeOut 为空,我将如何获取这些数据?

【问题讨论】:

  • 提示:您需要一个 OR 子句来涵盖该场景(即搜索时间在输入时间之后而输出时间为空的场景)
  • 如果假设是,如果 TimeOut 为 null 则返回记录,并且不关心使用过于疯狂的未来日期。你总是可以做一个 ISNULL(TimeOut, '2099-01-01')。否则,GMB 提供的答案是最好的路线。我的建议更像是一个你可以使用的愚蠢想法。

标签: sql sql-server tsql date


【解决方案1】:

TiemOut为null时,子查询中的条件变为:

where  @searchTime between TimeIn and null

这将始终评估为假(不少于null)。

一种解决方案是明确处理该用例:

select Count(ParkingSlotId) as 'Empty Spots' 
from [ParkingLot].[ParkingSlot] 
where ParkingSlotId not in (
    select ParkingSlotId 
    from [Transaction].[ParkingTransaction] 
    where 
        @searchTime >= TimeIn
        and ([TimeOut] is null or @searchTime <= [TimeOut])
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2011-07-04
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多