如何编写选择使它在两个时间段之间只返回一条记录

时间:2014-10-20 21:45:32

标签: sql firebird

我有这些数据

Table: Shifts
---------------------------------
Shift_Start       Shift_End
---------------------------------
6:00              16:30
16:45             22:15
22:15             6:00 (Next day) 
----------------------------------

我只需要选择一条当前时间介于shift_startshift_end

之间的记录

例如我试过

Select * from Shifts where current_time between shift_start and shift_end

Select first 1, shift_start, shift_end from Shifts 
order by shift_end - current_time

但是没有任何工作正常,任何想法?

2 个答案:

答案 0 :(得分:1)

也许这会做你想要的:

Select *
from Shifts
where shift_start < shift_end and current_time between shift_start and shift_end or
      shift_start > shift_end and not current_time between shift_start and shift_end;

如果问题确实是如何只获得一场比赛:

Select first 1 *
from Shifts
where shift_start < shift_end and current_time between shift_start and shift_end or
      shift_start > shift_end and not current_time between shift_start and shift_end;

编辑:

要先返回匹配的时间段,然后再返回任何其他时间段,您可以使用order by代替where

Select first 1 *
from Shifts
order by (case when shift_start < shift_end and current_time between shift_start and shift_end or
                    shift_start > shift_end and not current_time between shift_start and shift_end
               then 0 else 1
          end);

答案 1 :(得分:0)

我认为Firebird中的正确语法是ROWS 1 TO 1。另请参阅SELECT Rows

SELECT * 
  FROM Shifts 
 WHERE current_time BETWEEN shift_start AND shift_end
  ROWS 1