1. 程式人生 > >ORACLE初學第四篇

ORACLE初學第四篇

一、分組函式

select job,count(ename) as c_e from emp group by job;
/*分組函式一般是聯合聚合函式count來用的,上面的意思是:統計出emp下面不同工作的人數,顯示出不同的工作以及其統計數*/

二、過濾函式

/*在上面的例子中加上過濾條件*/
select job,count(ename) as c_e from emp group
by job having count(ename)>2;

三、排序函式

/*在上面的例子中在加上排序*/
select job,count(ename) as c_e from emp group by job having count(ename)>2 order by c_e desc;
//預設是asc進行排序的

四、子查詢

select sum(sal) 
from emp e 
where sal>(select avg(sal) from emp);

select count(sal) 
from emp e 
where 
sal>(select
avg(sal) from emp);
select job,count(sal) from emp e where sal>(select avg(sal) from emp) group by job; select job,count(sal) as cou_e from emp where sal>(select avg(sal) from emp) group by job having count(ename)>=2 order by cou_e desc; select job,count(sal) as cou_e from emp e where
sal>(select avg(sal) from emp sal>(select avg(sal) from emp where job='SALESMAN')) group by job having count(ename)>=2 order by cou_e desc;
//列印結果 JOB COU_E --------- ---------- ANALYST 2 MANAGER 2 //看起來上面的語句有些複雜,可能到時候我自己都不明白,所以我進行selectfromwhere每段進行換行的分開

五、聯合查詢

//去掉重複元素:並集
SQL> select * from a1
  2  union
  3  select * from a2;
//union all不去重複

//交集:intersect
select * from a1 intersect select * from a2;

//差集:minus(結果查詢到的是隻在第一個集合中二不在第二個集合中的元素)
select * from a1 minus select * from a2;

//表關聯查詢(查詢到的是每個表中的dept都不為空的資料)
select * from emp e,dept d where e.deptno=d.deptno;
//在ORACLE中效率更高的語句
select * from emp e inner join dept d on e.deptno=d.deptno;
//左連結left join(以左邊的表資料為準,在右邊有關聯的資料鏈接起來,沒有的就為空)
select * from emp e left join dept d on e.deptno=d.deptno;
//右關聯
select * from emp e right join dept d on e.deptno=d.deptno;
/*注意:實際開發中用左外聯接*/

六、EXISTS函式

select * from T_USER t where not exists(select * from t_user where t.id>=3);
//exists是用來判斷是否存在的,當exists(查詢)中的查詢存在結果時則返回真,否則返回假。not exists則相反。