ORACLE第七篇(日期函数)

一、日期两种类型简介

Date 和 timestamp(时间戳)
Date 包含信息 century(世纪信息) year 年 month 月 day 日 hour 小时 minute 分钟 second 秒
Timestamp 一般用于日期时间要求非常精确的情况,精确到毫秒级;
insert into t_date values(1,sysdate,systimestamp);
二、常用函数

 date 类型的常用函数:
 //查询系统日期两种格式
select sysdate from dual;
select systimestamp from dual;
Add_months 添加月份 select add_months(d1,2) from t_date where id=1;
Last_day 返回指定日期月份的最后一天 select last_day(d1) from t_date where id=1;
update t_date set d3=to_date('2016-12-20','YYYY-MM-DD') where id=1;
update t_date set d3=to_date('2016-12-20 18:31:34','YYYY-MM-DD HH24:MI:SS') where id=1;

Months_between 返回两个日期的相差月数 select months_between(d1,d3) from t_date where id=1;
select ceil(months_between(sysdate,to_date('2016-1-28','yyyy-mm-dd'))) from t_date where id=1;
------------------------------
                            18
next_day 返回特定日期之后的一周内的日期:select next_day(d1,2) from t_date where id=1;//返回下一周星期一的日期
Trunc 截取日期:
select trunc(d1,'YYYY') from t_date where id=1;
select trunc(d1,'MM') from t_date where id=1;
select trunc(d1,'DD') from t_date where id=1;
select trunc(d1,'HH') from t_date where id=1;
select trunc(d1,'MI') from t_date where id=1;
Extract 返回日期的某个域:
select extract(year from sysdate) from dual;
select extract(month from sysdate) from dual;
select extract(day from sysdate) from dual;
select extract(Hour from systimestamp) from dual;//返回的不是中国的时间
select extract(minute from systimestamp) from dual;
select extract(second from systimestamp) from dual;

To_char 将日期转换成字符串:
select to_char(d1,'YYYY-MM-DD') from t_date where id=1;
select to_char(d1,'YYYY-MM-DD HH24:MI:SS') from t_date where id=1;

//查询日期的最值的那一行的数值
select * from (select * from t_date order by d1) where id=1;

select * from t_date where d1=(select min(d1) from t_date);
//日期比较
select * from t_date where d1>to_date('2015-6-1','yyyy-mm-dd');
//比较年分
select * from t_date where extract(year from d1)>extract(year from to_date('2015-6-1','yyyy-mm-dd'));

补充EXISTS函数
我的理解是exists作为where条件时,先执行where的查询语句在一个个进行EXISTS里面的循环判断,EXISTS里面的where条件字段需要指明哪个表的不然默认是EXISTS里面sql语句from下面的表

猜你喜欢

转载自blog.csdn.net/qq_31681017/article/details/74697699