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)
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)
| 归档时间: |
|
| 查看次数: |
123407 次 |
| 最近记录: |