Oracle-trunc函数的用法

本文详细介绍了TRUNC函数的使用方法及实例,包括如何按不同时间精度(如分钟、小时、天等)聚合时间戳,以及如何在SQL查询中截取日期时间到不同的粒度。

 

 

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'),会提示“精度说明符过多”

转载于:https://www.cnblogs.com/lzfy/p/8485430.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值