Oracle - 获取当前月份的前3天记录

时间:2017-06-12 15:56:53

标签: sql database oracle oracle11g

我需要从Oracle数据库中获取当前月份的前3天记录。如下所示,

Select * from test.purchase where create_ts=( first 3 days of the current month)

2 个答案:

答案 0 :(得分:3)

您可以使用MM日期格式元素获取当月的第一天with the trunc(date) function

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;

答案 1 :(得分:2)

    Select * 
from test.purchase 
where create_ts between trunc(sysdate,'mm') and trunc(sysdate,'mm') + 3
相关问题