TRUNC函数用于对值进行截断。
用法有两种:TRUNC(NUMBER)表示截断数字,TRUNC(date)表示截断日期。
(1)截断数字:
格式:TRUNC(n1,n2),n1表示被截断的数字,n2表示要截断到那一位。n2可以是负数,表示截断小数点前。注意,TRUNC截断不是四舍五入。
SQL> select TRUNC(15.79) from dual;
TRUNC(15.79)
------------
15
SQL> select TRUNC(15.79,1) from dual;
TRUNC(15.79,1)
--------------
15.7
SQL> select trunc(15.79,-1) from dual;
TRUNC(15.79,-1)
---------------
10
(2)截断日期:
先执行命令:alter session set nls_date_format='yyyy-mm-dd hh24:mi:hh';
截取今天:
SQL> select sysdate,trunc(sysdate,'dd') from dual;
SYSDATE TRUNC(SYSDATE,'DD')
------------------- -------------------
2009-03-24 21:31:17 2009-03-24 00:00:00
截取本周第一天:
SQL> select sysdate,trunc(sysdate,'d') from dual;
SYSDATE TRUNC(SYSDATE,'D')
------------------- -------------------
2009-03-24 21:29:32 2009-03-22 00:00:00
截取本月第一天:
SQL> select sysdate,trunc(sysdate,'mm') from dual;
SYSDATE TRUNC(SYSDATE,'MM')
------------------- -------------------
2009-03-24 21:30:30 2009-03-01 00:00:00
截取本年第一天:
SQL> select sysdate,trunc(sysdate,'y') from dual;
SYSDATE TRUNC(SYSDATE,'Y')
------------------- -------------------
2009-03-24 21:31:57 2009-01-01 00:00:00
截取到小时:
SQL> select sysdate,trunc(sysdate,'hh') from dual;
SYSDATE TRUNC(SYSDATE,'HH')
------------------- -------------------
2009-03-24 21:32:59 2009-03-24 21:00:00
截取到分钟:
SQL> select sysdate,trunc(sysdate,'mi') from dual;
SYSDATE TRUNC(SYSDATE,'MI')
------------------- -------------------
2009-03-24 21:33:32 2009-03-24 21:33:00
获取上月第一天:
SQL> select TRUNC(add_months(SYSDATE,-1),'MM') from dual
一、数字作为参数
Trunc(number[, 小数位数] :直接截取,不进行四舍五入等操作
Round(number[, 小数位数]:截取的同时,进行四舍五入操作。
小数位数:正数,0,负数
// 89.98 89.99
select trunc(89.985, 2), round(89.985, 2) from dual;
// 89.9 90
select trunc(89.985, 1), round(89.985, 1) from dual;
// 89.9 89.9
select trunc(89.945, 1), round(89.945, 1) from dual;
// 89 90
select trunc(89.985, 0), round(89.985, 0) from dual;
// 89 90
select trunc(89.985), round(89.985) from dual;
// 80 90
select trunc(89.985, -1), round(89.985, -1) from dual;
// 0 100
select trunc(89.985, -2), round(89.985, -2) from dual;
一、用trunc函数处理日期
日期用例 '2008-11-28 12:59:59'周五
1.没有fmt部分时
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:00:01','YYYY-MM-DD hh24:mi:ss')) FROM DUAL;
结果: 2008-11-28
2.得到最当前日期之前的最近的一个周日的日期
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'D') FROM DUAL;
结果: 2008-11-23 周日
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'D')+1 FROM DUAL;
结果: 2008-11-24 周一
3.得到最当前日期的所在月份的第一天
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'MM') FROM DUAL;
结果: 2008-11-1
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'MM')-1 FROM DUAL;
结果: 2008-10-31
4.得到最当前日期的所在年份的第一天
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'Y') FROM DUAL;
结果: 2008-1-1
语句: SELECT TRUNC(TO_DATE('2008-11-28 12:59:59','YYYY-MM-DD hh24:mi:ss'),'Y')-1 FROM DUAL;
结果: 2007-12-31
二、用round函数处理日期
日期用例 '2008-11-28 11:59:59'周五
'2008-11-28 12:00:00'周五
'2008-11-28 11:59:59'周五
'2008-11-28 11:59:59'周五