如果不熟悉日期的操作,想要获取相应信息时,可能会写出复杂的 SQL , 比如求日期的月初时间
select hiredate,to_date(to_char(hiredate,'yyyy-mm')||'-1','yyyy-mm-dd') as 月初 from emp where rownum<=3;
其实这个一个函数即可解决,trunc()
select hiredate,trunc(hiredate,'mm') as 月初 from emp where rownum <= 3;
下面列举几个常用的日期取值方式
select hiredate,
to_number(to_char(hiredate,'hh24')) as 时,
to_number(to_char(hiredate,'mi')) as 分,
to_number(to_char(hiredate,'ss')) as 秒,
to_number(to_char(hiredate,'dd')) as 日,
to_number(to_char(hiredate,'mm')) as 月,
to_number(to_char(hiredate,'yyyy')) as 年,
to_number(to_char(hiredate,'ddd')) as 这天是年内第几天,
trunc(hiredate,'dd') as 一天之始, /*使用trunc函数处理前,需要先将类型转为date类型*/
trunc(hiredate,'day') as 这天的周初,
trunc(hiredate,'mm') as 这天的月初,
last_day(hiredate) as 这天的月末,
add_months(trunc(hiredate,'mm'),+1) as 下月初,
trunc(hiredate,'yy') as 年初,
to_char(hiredate,'day') as 星期标识,
to_char(hiredate,'month') as 月份
from(
select hiredate + 30/24/60/60 + 20/24/60 + 5/24 as hiredate from emp where rownum <= 1) x
上面 last_day 函数的用法需要注意的是,该函数返回的时分秒参数和源数据一样,并且用 last_day 函数作为区间条件会有下面问题:
数据如下所示
with t as (select to_date('1980-12-31 15:20:30','yyyy-mm-dd hh24:mi:ss') as d1,to_date('1980-12-31 05:20:30','yyyy-mm-dd hh24:mi:ss') as d2 from dual)
select d1,d2 from t;
如果要取一个月的数据,这么写的话,会有问题
with t as (select to_date('1980-12-31 15:20:30','yyyy-mm-dd hh24:mi:ss') as d1,to_date('1980-12-31 05:20:30','yyyy-mm-dd hh24:mi:ss') as d2 from dual)
select d1,d2 from t where d1 between trunc(d2,'mm') and last_day(d2);
应该这么写才行,也就是说 last_day 不能用于处理区间条件,否则会返回空行,可以用 < add_months(trunc(d2,'mm'),+1) 代替月末:
with t as (select to_date('1980-12-31 15:20:30','yyyy-mm-dd hh24:mi:ss') as d1,to_date('1980-12-31 05:20:30','yyyy-mm-dd hh24:mi:ss') as d2 from dual)
select d1,d2 from t where d1 >= trunc(d2,'mm') and d1 < add_months(trunc(d2,'mm'),+1);