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