0

我需要找出最接近的早上 7 点的日期。可以是今天(如果是 00-07AM)或明天(如果是 07AM-12PM)。有没有什么东西可以做这个“内联”而不是if声明?

4

2 回答 2

1

您可以在截断日期之前调整日期;用一些假sdate值代替真实值sysdate

alter session set nls_date_format = 'DD/MM/YYYY HH24:MI:SS';

with t as (
    select to_date('01/02/2013 00:00:00') as sdate from dual
    union all select to_date('01/02/2013 06:59:59') from dual
    union all select to_date('01/02/2013 07:00:00') from dual
    union all select to_date('01/02/2013 07:00:01') from dual
    union all select to_date('01/02/2013 23:59:59') from dual
    union all select to_date('02/02/2013 00:00:00') from dual
)
select sdate,
    trunc(sdate + interval '17' hour) + interval '7' hour
from t
order by sdate;

SDATE               TRUNC(SDATE+INTERVA
------------------- -------------------
01/02/2013 00:00:00 01/02/2013 07:00:00
01/02/2013 06:59:59 01/02/2013 07:00:00
01/02/2013 07:00:00 02/02/2013 07:00:00
01/02/2013 07:00:01 02/02/2013 07:00:00
01/02/2013 23:59:59 02/02/2013 07:00:00
02/02/2013 00:00:00 02/02/2013 07:00:00

所以trunc(sysdate + interval '17' hour)如果它在 07:00:00 之前给你今天午夜,如果它是 07:00:00 或之后给你明天午夜;然后+ interval '7' hour在第一个决定的那一天将其设为 07:00:00。

您可以使用+ 17/24and+ 7/24代替间隔,但我认为间隔更容易让人们以后理解。

这假设如果您恰好在 07:00:00 运行它,则算作明天;如果那是错误的,那么您可以调整一秒钟:

with t as (
    select to_date('01/02/2013 00:00:00') as sdate from dual
    union all select to_date('01/02/2013 06:59:59') from dual
    union all select to_date('01/02/2013 07:00:00') from dual
    union all select to_date('01/02/2013 07:00:01') from dual
    union all select to_date('01/02/2013 23:59:59') from dual
    union all select to_date('02/02/2013 00:00:00') from dual
)
select sdate,
    trunc(sdate + interval '16:59:59' hour to second) + interval '7' hour
from t
order by sdate;

SDATE               TRUNC(SDATE+INTERVA
------------------- -------------------
01/02/2013 00:00:00 01/02/2013 07:00:00
01/02/2013 06:59:59 01/02/2013 07:00:00
01/02/2013 07:00:00 01/02/2013 07:00:00
01/02/2013 07:00:01 02/02/2013 07:00:00
01/02/2013 23:59:59 02/02/2013 07:00:00
02/02/2013 00:00:00 02/02/2013 07:00:00
于 2013-02-01T13:00:45.663 回答
0

如果时间 < 07:00 或明天,这将给您今天。

trunc(sysdate+17/24)

trunc 删除日期的时间部分。17/24 为当前时间增加 17 小时。

于 2013-02-01T13:00:11.197 回答