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