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