oracle函数trunc的使用

1、日期比较时精确到日,可以使用 TRUNC(sysdate,'dd')函数。
函数支持格式有:yyyy MM  dd  hh Mi
可以用 select TRUNC(sysdate,'yyyy') from dual  看看结果是什么。

不要按下面的方式比较日期:
TO_DATE(TO_CHAR(LOGTIME,'YYYY-MM-DD'), 'YYYY-MM-DD') < TO_DATE(TO_CHAR(SYSDATE - $DAYNUM$,'YYYY-MM-DD'), 'YYYY-MM-DD')

 

2、trunc(d1[,c1])  返回日期d1所在期间(参数c1)的第一天日期

d1日期型,c1为字符型(参数),c1默认为j(即当前日期)

c1对应的参数表:

本周星期日:day或dy或d (每周顺序:日,一,二,三,四,五,六)

本月初日期:month或mon或mm或rm

本季日期:q

本年初日期:syear或year或yyyy或yyy或yy或y(多个y表示精度) 

本世纪初日期:cc或scc

【返回】:日期
select sysdate from dual --当时日期

select trunc(sysdate) from dual

select trunc(sysdate ,'DD') from dual --今天日期

select trunc(sysdate,'d')+7 from dual --本周星期日

select trunc(sysdate,'dy')+7 from dual  --本周星期日

select trunc(sysdate,'day')+7 from dual --本周星期日

select trunc(sysdate,'q') from dual--本季开始日期

select trunc(sysdate,'month') from dual --本月开始日期

select trunc(sysdate ,'mm') from dual --本月开始日期

select trunc(sysdate,'year') from dual  --本年开始日期

select trunc(sysdate ,'yyyy') from dual --本年开始日期

select trunc(sysdate ,'HH24') from dual --本小时开始时间

select trunc(sysdate ,'MI') from dual --本分钟开始时间

select trunc(sysdate ,'CC') from dual --本世纪开始时间

select trunc(LAST_DAY(sysdate),'dd') from dual --本月最后一天

3、round(10.2356,2)函数可以对数字按指定保留小数位数四舍五入,这个函数还可以对日期四舍五入
select round(sysdate,'yyyy') from dual 四舍五入到年

select round(sysdate,'mm') from dual 四舍五入到月

select round(sysdate,'dd') from dual 四舍五入到日

select round(sysdate,'hh') from dual 四舍五入到小时

select round(sysdate,'mi') from dual 四舍五入到分钟

4、TRUNC还可以对number类型使用,
TRUNC(89.985,2)=89.98
TRUNC(89.985)=89
TRUNC(89.985,-1)=80

 

 --Oracle trunc()函数的用法
/**************日期********************/
1.select trunc(sysdate) from dual  --2011-3-18  今天的日期为2011-3-18
2.select trunc(sysdate, 'mm')   from   dual  --2011-3-1    返回当月第一天.
3.select trunc(sysdate,'yy') from dual  --2011-1-1       返回当年第一天
4.select trunc(sysdate,'dd') from dual  --2011-3-18    返回当前年月日
5.select trunc(sysdate,'yyyy') from dual  --2011-1-1   返回当年第一天
6.select trunc(sysdate,'d') from dual  --2011-3-13 (星期天)返回当前星期的第一天
7.select trunc(sysdate, 'hh') from dual   --2011-3-18 14:00:00   当前时间为14:41   
8.select trunc(sysdate, 'mi') from dual  --2011-3-18 14:41:00   TRUNC()函数没有秒的精确
/***************数字********************/
/*
TRUNC(number,num_digits) 
Number 需要截尾取整的数字。 
Num_digits 用于指定取整精度的数字。Num_digits 的默认值为 0。
TRUNC()函数截取时不进行四舍五入
*/
9.select trunc(123.458) from dual --123
10.select trunc(123.458,0) from dual --123
11.select trunc(123.458,1) from dual --123.4
12.select trunc(123.458,-1) from dual --120
13.select trunc(123.458,-4) from dual --0
14.select trunc(123.458,4) from dual  --123.458
15.select trunc(123) from dual  --123
16.select trunc(123,1) from dual --123
17.select trunc(123,-1) from dual --120

猜你喜欢

转载自xuqiong1.iteye.com/blog/2051815