上个月的Oracle日期函数

use*_*860 14 sql oracle sql-date-functions

我有下面的查询,其中日期是硬编码的.我的目标是删除已编码的日期; 查询应该在运行时拉取上个月的数据.

select count(distinct switch_id)
  from xx_new.xx_cti_call_details@appsread.prd.com
 where dealer_name =  'XXXX'
   and TRUNC(CREATION_DATE) BETWEEN '01-AUG-2012' AND '31-AUG-2012'
Run Code Online (Sandbox Code Playgroud)

我应该使用sysdate-15功能吗?

小智 44

稍微修改Ben的查询,

 select count(distinct switch_id)   
  from xx_new.xx_cti_call_details@appsread.prd.com  
 where dealer_name =  'XXXX'    
   and creation_date between add_months(trunc(sysdate,'mm'),-1) and last_day(add_months(trunc(sysdate,'mm'),-1))
Run Code Online (Sandbox Code Playgroud)

  • @BoydDensmore不幸的是,答案*会错过本月最后一天的所有数据.但是,通过使用加号运算符来添加1以便获得下个月第一天的开始是一个非常简单的问题,如下所示:`(last_day(add_months(trunc(sysdate,'mm) "), - 1))+ 1)`. (4认同)
  • 使用last_day()和trunc()会给你最后一天的开头,那就是你想要的吗?对我来说,它给了我last_day(add_months(trunc(sysdate,'mm'), - 1))给了我2015年7月31日00:00:00.如果我在中间使用它,我会错过7月31日的所有数据. (2认同)

Ben*_*Ben 11

trunc()函数将日期截断到指定的时间段; 所以trunc(sysdate,'mm')会返回当月的开头.然后,您可以使用该add_months()函数获取上个月的开头,如下所示:

select count(distinct switch_id)   
  from xx_new.xx_cti_call_details@appsread.prd.com  
 where dealer_name =  'XXXX'    
   and creation_date >= add_months(trunc(sysdate,'mm'),-1) 
   and creation_date < trunc(sysdate, 'mm')
Run Code Online (Sandbox Code Playgroud)

作为一个小方面,你没有明确地转换为原始查询中的日期.例如,使用日期文字或例如函数,始终执行此操作.如果你不这样做,你肯定会在某些时候弄错.DATE 2012-08-31to_date()to_date('2012-08-31','YYYY-MM-DD')

您不会使用,sysdate - 15因为这将提供当前日期之前15天的日期,这似乎不是您所追求的.它还包括您不使用的时间组件trunc().


正如一点点演示trunc(<date>,'mm'):

select sysdate
     , case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as gt
     , case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as lt
     , case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as eq
  from dual
       ;

SYSDATE                   GT         LT         EQ
----------------- ---------- ---------- ----------
20120911 19:58:51                                1
Run Code Online (Sandbox Code Playgroud)