我想选择具有特定时间间隔的行,但是日期并不重要。因此,我需要一个仅返回时间部分的函数。我尝试使用:
to_char(mydate, 'HH12:MI:SS') between '00:00:00' and '08:00:00'
但是这似乎不起作用。有什么想法吗?
答案 0 :(得分:5)
通过一些示例数据,您可以看到使用HH12
不一定会产生您期望的字符串:
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
-- CTE just for dummy data
with mytable (mydate) as (
select cast(timestamp '2018-08-01 00:00:00' as date) from dual
union all select cast(timestamp '2018-08-02 07:59:59' as date) from dual
union all select cast(timestamp '2018-08-03 08:00:00' as date) from dual
union all select cast(timestamp '2018-08-04 08:00:01' as date) from dual
union all select cast(timestamp '2018-08-05 19:59:59' as date) from dual
union all select cast(timestamp '2018-08-06 20:00:00' as date) from dual
union all select cast(timestamp '2018-08-07 20:00:01' as date) from dual
)
-- actual query
select mydate,
to_char(mydate, 'HH24:MI:SS') as time_24,
to_char(mydate, 'HH12:MI:SS') as time_12
from mytable;
MYDATE TIME_24 TIME_12
------------------- -------- --------
2018-08-01 00:00:00 00:00:00 12:00:00
2018-08-02 07:59:59 07:59:59 07:59:59
2018-08-03 08:00:00 08:00:00 08:00:00
2018-08-04 08:00:01 08:00:01 08:00:01
2018-08-05 19:59:59 19:59:59 07:59:59
2018-08-06 20:00:00 20:00:00 08:00:00
2018-08-07 20:00:01 20:00:01 08:00:01
因此,当您尝试使用基于HH12的字符串进行过滤时,它会包含您在8am到8pm之间不会看到的记录;并且不包括午夜(因为这是“ 12:00:00”而不是“ 00:00:00”):
select mydate
from mytable
where to_char(mydate, 'HH12:MI:SS') between '00:00:00' and '08:00:00';
MYDATE
-------------------
2018-08-02 07:59:59
2018-08-03 08:00:00
2018-08-05 19:59:59
2018-08-06 20:00:00
如果您改用HH24
,则会得到
select mydate
from mytable
where to_char(mydate, 'HH24:MI:SS') between '00:00:00' and '08:00:00';
MYDATE
-------------------
2018-08-01 00:00:00
2018-08-02 07:59:59
2018-08-03 08:00:00
此外,请注意between
是包含性的,因此它将在恰好08:00:00提取记录。那可能不是您想要的-如果将一天分为三个8小时时段,则不会在那一秒内多次记录数据;因此您可以改用更明确的范围:
select mydate
from mytable
where to_char(mydate, 'HH24:MI:SS') >= '00:00:00'
and to_char(mydate, 'HH24:MI:SS') < '08:00:00';
MYDATE
-------------------
2018-08-01 00:00:00
2018-08-02 07:59:59
那么您的第二个班次是:
where to_char(mydate, 'HH24:MI:SS') >= '08:00:00'
and to_char(mydate, 'HH24:MI:SS') < '16:00:00';
您的第三班次是:
where to_char(mydate, 'HH24:MI:SS') >= '16:00:00';
或者,如果您愿意,还可以保持一致性:
where to_char(mydate, 'HH24:MI:SS') >= '16:00:00'
and to_char(mydate, 'HH24:MI:SS') < '24:00:00';
您永远无法将小时报告为24,但这是字符串无关紧要的问题,尽管有点刺耳。
答案 1 :(得分:-1)
TO_CHAR(mydate, 'HH24:MI:SS')
WHERE mydate BETWEEN '00:00:00' AND '08:00:00';