Oracle入门指南_4
select deptno,dname,loc from dept;--查询scott用户默认的dept表中的所有记录
select * from dept;
?
Where条件查询:select deptno,dname,loc from dept where deptno=10;--查询deptno=10的记录
?
比较运算符select * from emp where deptno between 10 and 20;--查询emp表中的deptno在10-20之间的,包括10,20select * from emp where job like '_A%';--匹配第二个字符为'A'的select * from emp where job like '_a%';--匹配第二字符为'a'的--字符匹配是区分大小写的select * from emp where mgr is null;select * from emp where mgr is not null;
?
逻辑运算符select * from emp where mgr is not null and sal>1500;--查询mgr is not null的并且 sal>1500的数据--not是取反的意思
?
select * from emp order by hiredate desc;--根据入职时间降序排
?
函数:字符函数lower:转换为小写upper:大写initcap:首字符大写concat:连接字符串substr(column_name,startIndex,count):对于column_name列从第startIndex开始截取count个显示length:字符串的长度trim:去掉左右的空格ltrim:去掉左边的空格rtrim:去掉右边的空格select concat('你好',ename),lower(ename),upper(ename),initcap(ename),substr(ename,1,1),length(ename),trim(ename) from emp;
select length(ename),length(trim(ename)) from emp;--函数是可以嵌套的
?
数值函数round(num,n):将列或表达式所表示的数值四舍五入到小数点后几位trunc(num,n):将列或表达式的数值截取到小数点的后几位,而不进行四舍五入mod(m,n):m除以n以后的余数select round(49.255,2),round(49.254,2),trunc(49.256,2),mod(3,2) from dual;--49.26 49.25 49.25 1select round(12.00,2) from dual;--12,若为0则直接忽略0select round(sal,2) from emp;
?
数据类型转换函数to_char(date|number,[fmt]):将日期或数值型按照模式 fmt 转换为变长字符串to_number(char):将一个有数字组成的字符串转换为数值to_date(char,[fmt]):将yi8ge表示日期的字符串按照模式 fmt 转换为日期select to_char(sysdate,'yyyy-MM-dd HH-mm-ss day d q') from dual;--2013-10-10 10-10-19 星期四 5 4
select to_char(892343354) from dual;select to_char(892343354,'L999,999,999,999') from dual;--¥892,343,354 根据本地货币转换select to_char(892343354,'L999,999,999,999.99') from dual;--¥892,343,354.00
select * from emp where to_char(hiredate,'MM')='12';--获取12月份入职的 员工
select to_number('123')+1 from dual;--将字符型,转为number型 124
?
select to_date('1991-2-15','yyyy/MM/dd') from dual;--1991/2/15
?
日期函数sysdate:获取当前时间months_between(date1,date2):date1与date2之间的月数add_months(date,n):向date加上n个月,是几月份next_day(date,c):求出date之后一周内星期c的日期;周日是星期1,周六是星期7 ?c=1-7之间的数last_day(date):求出date所在月的最后一天select to_char(sysdate,'yyyy-MM-dd HH:mm:ss') from dual;--2013-10-10 11:10:31select to_char(sysdate,'yyyy/MM/dd HH:mm:ss') from dual;--2013/10/10 11:10:45
?
select months_between(sysdate,to_date('2010-01-01','yyyy-MM-dd')) from dual;--45.3055073924731 46个月不到
?
select add_months(sysdate,2) from dual;--2013/12/10 11:29:06
?
select next_day(sysdate,7) from dual;--2013/10/12 11:34:18 本周周六是10/12
?
select last_day(sysdate) from dual;--10-31
?
其他函数nvl:当一个值为null时,显示预先定义的值select nvl(mgr,'0') from emp;
?
?聚合函数avg:求平均count:统计数量max:最大值min:最小值sum:求和select count(*) from emp;select sum(sal) from emp;select min(sal) from emp;
?
分组查询--统计每个部门的平均销售额select avg(sal),deptno from emp group by deptno;--显示平均销售额在2000以上的部门select avg(sal),deptno from emp group by deptno having avg(sal)>2100;
?
总结:查询数据根据条件查询数据查询排序常见的函数