Oracle-trunc函数的用法


 

 

trunc 函数可用于截取日期时间

用法:trunc(字段名,精度)

具体实例:

 

-- 按1分钟聚合
select  trunc(stime,  'MI' as  stime
 
-- 按1小时聚合
select  trunc(stime,  'HH' as  stime
 
-- 按1天聚合
select  trunc(stime,  'DD' as  stime
 
-- 示例
select  trunc( cast ( '2017-11-09 17:42:57'  as  timestamp ),  'MI' as  stime

select trunc('2017-11-09 17:42:57', 'MI') as stime   两个查询语句 数据结果一样

--返回结果
2017-11-09 17:42:00
 
-- 按5分钟聚合
trunc(minutes_sub(stime,  minute (stime) % 5),  'MI' )
 
-- 按10分钟聚合
trunc(minutes_sub(stime,  minute (stime) % 10),  'MI' )
 
-- 示例
select  trunc(minutes_sub( '2017-11-09 17:46:57' minute ( '2017-11-09 17:46:57' ) % 5),  'MI' )
--返回结果
2017-11-09 17:45:00
 
 
 

在表table1中,有一个字段名为sysdate,该行id=123,日期显示:2016/10/28 15:11:58

1、截取时间到年时,sql语句如下:

select trunc(sysdate,'yyyy') from table1 where id=123;  --yyyy也可用year替换

显示:2016/1/1

2、截取时间到月时,sql语句:

select trunc(sysdate,'mm') from table1 where id=123;

显示:2016/10/1

3、截取时间到日时,sql语句:

select trunc(sysdate,'dd') from table1 where id=123;

显示:2016/10/28

4、截取时间到小时时,sql语句:

select trunc(sysdate,'hh') from table1 where id=123;

显示:2016/10/28 15:00:00

5、截取时间到分钟时,sql语句:

select trunc(sysdate,'mi') from table1 where id=123;

显示:2016/10/28 15:11:00

6、截取时间到秒暂时不知道怎么操作

7、不可直接用trunc(sysdate,'yyyy-mm-dd'),会提示“精度说明符过多”


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM