甲骨文 - 获取当月的前 3 天记录



我需要从 Oracle 数据库中获取当月的前 3 天记录。像下面这样,

Select * from test.purchase where create_ts=( first 3 days of the current month)
Select * 
from test.purchase 
where create_ts between trunc(sysdate,'mm') and trunc(sysdate,'mm') + 3

您可以使用trunc(date)函数获取当前月份的第一天,使用MM日期格式元素。

select to_char(trunc(sysdate, 'MM'), 'YYYY-MM-DD Hh24:MI:SS') from dual;
TO_CHAR(TRUNC(SYSDA
-------------------
2017-06-01 00:00:00

然后,您可以使用日期算术添加表示该数字的天数或间隔,以获得该月的第四天:

select to_char(trunc(sysdate, 'MM') + 3, 'YYYY-MM-DD Hh24:MI:SS') from dual;
TO_CHAR(TRUNC(SYSDA
-------------------
2017-06-04 00:00:00

如果你想要第四天开始的数据,即3日23:59:59之前的数据,你可以查找小于4日午夜的值:

select * from test.purchase
where create_ts >= trunc(sysdate, 'MM')
and create_ts < trunc(sysdate, 'MM') + 3;

您可能会使用between,但由于它是包容性的,您需要在 3 日指定绝对最晚时间 - 检查该列是日期还是时间戳,这可能会发生变化,并且可能有点混乱。如果您使用between trunc(sysdate, 'MM') and trunc(sysdate, 'MM') + 3那么您将在 4 日午夜包含任何记录,这不是您想要的。我发现使用>=<更清晰,更少歧义,即使它多打字一点。

如果列实际上是时间戳,那么您也可以将计算的日期转换为时间戳,和/或上限的使用间隔:

select * from test.purchase
where create_ts >= cast(trunc(sysdate, 'MM') as timestamp)
and create_ts < cast(trunc(sysdate, 'MM') + 3 as timestamp);

。或:

...
and create_ts < cast(trunc(sysdate, 'MM') as timestamp) + interval '3' day;

最新更新