1. 程式人生 > >Oracle-trunc函數的用法

Oracle-trunc函數的用法

lai sub line 截取時間 number clas 小時 顯示 select

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‘),會提示“精度說明符過多”

Oracle-trunc函數的用法