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
===================================================================
--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
原文來自於:https://blog.csdn.net/haiross/article/details/12837033