一、分组函数
在oracle中,我们常用的分组函数有:count、max、min、avg、sum,下面结合例子逐一讲解。
1、count函数在分页和求结果集条数时经常用到。
--1.查询员工表人数 select count(1) from emp; --返回匹配条件的记录的条数,会忽略值为null的行 select count(comm) from emp; --2.统计员工表中职务的个数 select count(distinct job) from emp;
2、max、min、avg、sum函数分别用于求最大值、最小值、平均值和求和。
--3.查询最高工资、最低工资和平均工资 select max(sal),min(sal),avg(sal) from emp; --4.查询工资高于平均工资的员工 select * from emp where sal>(select avg(sal) from emp) --5.对工资求和 select sum(sal) from emp;
3、分组函数和group by会经常一起使用,对查询的结果进行分组统计。
--6.查询每个部门的员工总数 select deptno,count(1) from emp group by deptno --7.显示每个部门的最高工资和最低工资 select deptno,max(sal),min(sal) from emp group by deptno; --8.显示每个部门的每个岗位的最高工资和最低工资 select deptno,job,max(sal),min(sal) from emp group by deptno,job order by deptno --9.查出每个部门比它所在部门的平均工资高的员工 select e1.* from emp e1, (select deptno, avg(sal) avgsal from emp group by deptno) e2 where e1.deptno = e2.deptno and e1.sal > e2.avgsal
4、having用于对分组后的结果进行筛选。
--8.显示每个部门的平均工资,筛选出平均工资高于2000的部门 select deptno,avg(sal) from emp group by deptno having avg(sal)>2000
注意:1.如果一个查询语句中使用了 order by、 group by、 having,他们的顺序 [where] group by having order by
2.如果一个查询语句使用了group by 那么该语句查询的列只能是分组函数或者被分组的列。
二、数字函数
--1.求绝对值 abs select abs(100),abs(-100) from dual;--伪表 --2.求平方根 sqrt select sqrt(sal),sqrt(comm) from emp; --3.求幂 power select power(3,2),power(2,3) from dual; --4.四舍五入(第二个参数代表小数位数) round select round(55555.66666,2),round(55555.66666) from dual;
三、字符函数
--1.连接字符串 select ‘0731-‘||‘8888888‘ from dual select concat(‘0731-‘,‘8888888‘) from dual; --2.替换字符串 select replace(‘He Love You!‘,‘He‘,‘I‘) from dual; --3.截取字符串 substr(str,position,length) position从1开始 select substr(‘1234567890‘,2,3) from dual --4.转换成大写 select upper(‘abcDEFgHiJKlmn‘) from dual; --5.转换成小写 select lower(‘abcDEFgHiJKlmn‘) from dual;
四、转换函数
--1.将字符串转换成日期 --to_date(值,格式) Y代表年 M代表月 D代表天 yyyy-mm-dd hh24:mi:ss --上午/下午是根据语言集来的。 AM/PM select to_date(‘20150625‘,‘yyyymmdd‘), to_date(‘2015.06.25‘,‘yyyy.mm.dd‘), to_date(‘20150625222930‘,‘yyyymmddhh24miss‘), to_date(‘2015-06-25 10:30:15 下午‘,‘yyyy-mm-dd hh12:mi:ss PM‘) from dual; --2.将日期转换成字符串 --to_char(值,格式) SELECT TO_CHAR(SYSDATE,‘YYYY-MM-DD‘) FROM DUAL SELECT TO_CHAR(SYSDATE,‘HH24:MI‘) FROM DUAL SELECT TO_CHAR(SYSDATE,‘MM‘) FROM DUAL --获取星期 select to_char(sysdate,‘day‘) from dual;
五、日期函数
--获取在系统日期基础上再加若干个月后的新日期(加月份) add_months select sysdate,add_months(to_date(‘2016-02-29‘,‘yyyy-mm-dd‘),12) from dual; --获取当前日期所在月份的最后一天的日期 select sysdate,last_day(to_date(‘2016-08‘,‘yyyy-mm‘)) from dual; --两个日期的相差月份 select sysdate,months_between(to_date(‘2015-08‘,‘yyyy-mm‘),to_date(‘2016-03‘,‘yyyy-mm‘)) from dual --截取日期的指定部分 select extract(YEAR FROM SYSDATE) FROM DUAL select extract(Month FROM date ‘2011-3-16‘) FROM DUAL select extract(hour FROM timestamp ‘2015-2-16 11:22:33‘) FROM DUAL --minute second day month year
oracle之分组函数、数字函数、字符函数、转换函数和日期函数
原文:http://www.cnblogs.com/wanglitao/p/4870534.html