--========================================================
--ylb:Oracle
--17:13 2011-12-30
--1,子查詢(嵌套子查詢、相關(guān)子查詢)
--========================================================
/***
連接與子查詢的區(qū)別:
1,當(dāng)需要多個表的數(shù)據(jù)時用連接,子查詢只能返回單表數(shù)據(jù)。
2,連接快,子查詢慢。
3,子查詢功能強大。
4,子查詢-兩種(嵌套子查詢,關(guān)聯(lián)子查詢)
嵌套簡單,關(guān)聯(lián)復(fù)雜,面試關(guān)聯(lián)查詢
**/
--一, 子查詢第一種 : 嵌套子查詢:簡單--子查詢可以獨立運行,自內(nèi)而外
--1,查詢工資高于SMITH工資的所有員工
select * from emp where sal>( select sal from emp where enAme= 'SMITH' )
go
--2,查詢工資高于公司平均工資的所有員工?
select * from emp where sal>( select avg (sal) from emp)
--附加題,
--> >= < <= = != <> ^= 后面只能跟一個值,
--如果有多個值,>all--大于最大值 >any--大于最小值
--查詢工資高于所有部門的平均工資的員工
select * from emp where sal> all ( select avg (sal) from emp group by deptno)
--查詢工資高于任何部門的平均工資的員工
select * from emp where sal> any ( select avg (sal) from emp group by deptno)
go
/*********************************************************************************/
--二, 子查詢第二種 : 關(guān)聯(lián)子查詢 ,思考:自外而內(nèi)
--3,查詢工資高于本部門平均工資的所有員工?
select * from emp a where a.sal>( select avg (sal) from emp where deptno=a.deptno)
--4,查詢本部門最高工資的員工?(三種方法)
--方法一,使用嵌套子查詢(非關(guān)聯(lián)子查詢)
select * from emp a where (a.deptno,a.sal) in ( select deptno, max (sal) from emp group by deptno)
--方法二,使用關(guān)聯(lián)子查詢/*9-******************
select * from emp a where a.sal=( select max (sal) from emp where deptno=a.deptno)
--方法三,使用關(guān)聯(lián)子查詢的名次問題,名次=人數(shù)+1
sal=800
deptno=20
select * from emp a
where (
select count (*) from emp
where deptno=a.deptno and sal>a.sal)=1
/*********************************************************************************/
go
--補充題:
--查詢本部門第二高工資的員工?(一種方法)
--5,查詢本部門最低工資的員工 ?
select * from emp a where ( select count (*) from emp where deptno=a.deptno and sal<a.sal)=0
------------------------------------------------------三,select 語句做表達(dá)式
--6,統(tǒng)計每個部門的信息和人數(shù)?
select a.*,( select count (*) from emp where deptno=a.deptno) 人數(shù) from dept a
select a.* from dept a
select a.deptno,b.dname,b.loc, count (*) from emp a,dept b where a.deptno=b.deptno group by a.deptno,b.dname,b.loc
--7,統(tǒng)計每個部門工資在(500-1000)/(1000-3500)/(3500-7000) 的人數(shù)?
select a.*,
( select count (*) from emp where deptno=a.deptno and sal>500 and sal<=1000) '500-1000' ,
( select count (*) from emp where deptno=a.deptno and sal>1000 and sal<=3500),
( select count (*) from emp where deptno=a.deptno and sal>3500 and sal<=7000)
from dept a
|