2010년 5월 19일

Subquery (서브쿼리)

원리:안의 서브 쿼리가 먼저 실행되어져서 걸러진 데이터로, 바깥 메인 쿼리와 비교한다.
서브쿼리는 반드시 ()로 묶는다,

문제)이순신과 같은 부서에서 근무하는 사람
select saname, deptno from sawon
where deptno=(select deptno from sawon
where saname='이순신')

문제)sawon 테이블에서 급여가 평균보다 큰 사람
select * from sawon
where sapay>(select avg(sapay) from sawon)

문제)sawon테이블에서 '공부만'과 같은 부서(deptno)에 근무하는 사람찾기
select saname,deptno,sajob from sawon
where deptno=(select deptno from sawon where saname='공부만')

문제) 공부만과 같은 부서 및 공부해와 같은 직급
select saname,deptno,sajob from sawon
where deptno=(select deptno from sawon where saname='공부만')
and sajob=(select sajob from sawon where saname='공부해')

문제) 공부해와 같은 부서 및 같은 직급, 단 김유신 제외
select saname,deptno,sajob from sawon
where (deptno=(select deptno from sawon where saname='공부해')
and sajob=(select sajob from sawon where saname='공부해'))
and saname!=(select saname from sawon where saname='김유신')

문제) sawon 테이블에서 급여가 가장 많은 사람 찾기
select saname,deptno,sajob,sapay from sawon
where sapay=(select max(sapay) from sawon)

문제) sawon테이블에서 직책이 '사원'중 급여가 가장 많은 사람은?
select * from sawon
where sajob='사원' and sapay=(select max(sapay) from sawon where sajob='사원')

문제)10번 부서에서 전체 부서의 평균급여보다 급여가 적은 사람 찾기
select saname, sapay from sawon
where deptno=10 and sapay<(select avg(sapay) from sawon)

문제)전체 부서에서 10번부서의 평균급여보다 급여가 적은사람 찾기
select saname, sapay from sawon
where sapay<(select avg(sapay) from sawon where deptno=10)

문제)전체부서에서 전체부서의 평균급여보다 급여가 적은 사람 찾기
select saname, sapay from sawon
where sapay<(select avg(sapay) from sawon)

문제)20번 부서에서 10번부서의 최소급여보다 급여가 많은 사람 찾기
select saname, sapay, deptno from sawon
where deptno=20 and sapay>(select min(sapay) from sawon where deptno=10)

문제)10번 부서의 직책이 '사원'인 사람중에서 '사원'의 평균급여보다 급여가 적은 사람 찾기
select saname, sajob, saname, deptno, sapay from sawon
where (deptno=10 and sajob='사원') and sapay<(select avg(sapay) from sawon where sajob='사원')

댓글 없음:

댓글 쓰기