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
example:
--每天的短信发送量统计
select trunc(t.dtime),
count(*)
from t_uoa_alarmlog t where t.dtime>to_date('2010-07-02 12:00:00', 'yyyy-mm-dd hh24:mi:ss')
group by trunc(t.dtime);