2017-06-12 483 views
0

我需要从Oracle数据库中获取当前月份的前3天记录。类似下面,Oracle - 获取当月的前3天记录

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

欢迎来到SO。你有什么尝试? –

+0

我尝试提供那些(3时间戳),但当月更改时,我需要编辑查询。 – karikevinod

回答

2
Select * 
from test.purchase 
where create_ts between trunc(sysdate,'mm') and trunc(sysdate,'mm') + 3 
+0

当然,由于“between”是包含性的,因此这将包括4日午夜的任何记录。这可能对OP的数据不是问题;或者所有的值都是在午夜,在这种情况下'+ 2'可以起作用。 –

3

你可以得到当月​​的第一天,使用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 

如果你想要的数据高达那第四天开始,即达到23:59:59 3日,你可以看看值小于午夜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;