SUBQUERY
: SQL문 안의 select문을 서브쿼리라고 한다. 꼭 ( )로 묶어야 한다.
-where절에 비교연산자 오른쪽에 입력
-having절에 비교연산자 오른쪽에 입력
-서브쿼리 컬럼명에 main 쿼리에 없는 컬럼명을 사용하지 못함.(where절은 가능)
중첩서브쿼리(nested subquery)
-inner query(subquery) 먼저 수행. inner query 수행한 값 가지고 main query 수행
main query, outer query
select *
from employees
where salary > (select salary
from employees
where employee_id =100);
subquery, inner query
단일행 서브쿼리
: 서브쿼리의 결과가 한 개의 값이 나오는 서브쿼리
-단일행 비교연산자 : =,>,≥,<,≤,!=,<>,^=
여러행 서브쿼리
: 서브쿼리의 결과가 여러개의 값이 나오는 서브쿼리
-여러행 비교연산자 : in(=or), >any, <any, =any, >all, <all
① any의 속성은 or 논리연산자의 의미를 내포하고 있다.
: >any = > or > or > ... = > min( ) 최소값보다 큼 역할
<any = < or < or < ... = < max( ) 최대값보다 작음 역할
② all의 속성은 and 논리연산자의 의미를 내포하고 있다.
: >all = > and > and > ... = >max( ) 최대값보다 큼 역할
<all = < and < and < ... = <min( ) 최소값보다 작음 역할
주의할 점
-그룹함수는 두번 중첩하게 되면 개별컬럼은 사용할 수 없음. 서브쿼리는 가능
[문제52] 급여의 최소 평균값을 가지고 있는 부서번호, 평균을 출력하기
select department_id, avg(salary)
from employees
group by department_id
having avg(salary) = (select min(avg(salary))
from employees
group by department_id);
-IN(= or = or = ...) 과 NOT IN(≠ and ≠ and ≠ ... ) 연산자 차이
or 진리표
and 진리표
[문제53] 110번 사원의 job_id와 동일한 사원들 중에 110번 사원의 급여보다 더 많이 받는 사원들의 정보를 추출하세요.
select *
from employees
where salary > (select salary
from employees
where employee_id =110)
and job_id = (select job_id
from employees
where employee_id =110) ;
[문제54] 최고 급여를 받는 사원들의 정보를 출력해주세요.
select *
from employees
where salary = (select max(salary)
from employees);
[문제56] 2006년도에 입사한 사원들의 job_id와 동일한 사원들의 job_id별 급여의 총액 중에 50000 이상인 값만 출력해주세요.
select job_id, sum(salary)
from employees
where job_id in (select job_id
from employees
where hire_date >= to_date('2006/01/01','yyyy-mm-dd')
and hire_date < to_date('2007/01/01','yyyy-mm-dd')
group by job_id
having sum(salary) >= 50000;
[문제57] location_id 가 1700인 모든 사원들의 last_name, department_id, job_id를 출력해주세요.
select last_name, department_id, job_id
from employees
where department_id in (select department_id
from departments
where location_id=1700);
[문제58] 60번 부서 사원들의 급여 보다 더 많은 급여를 받는 사원들의 정보를 출력해주세요.
select *
from employees
where salary > (select max(salary)
from employees
where department_id = 60);
[문제59] 관리자 사원들의 정보를 출력해주세요.
select *
from employees
where employee_id in (select manager_id
from employees);
[문제60] 관리자가 아닌 사원들의 정보를 출력해주세요.
select *
from employees
where employee_id not in (select manager_id
from employees
where manager_id is not null);
'SQL' 카테고리의 다른 글
[Oracle] INLINE VIEW (0) | 2021.12.27 |
---|---|
[Oracle] 서브쿼리 - 상호관련 서브쿼리(correlated subquery) (0) | 2021.12.24 |
[Oracle] ANSI 조인 (0) | 2021.12.24 |
[Oracle] Oracle 조인 (0) | 2021.12.23 |
[Oracle] 그룹함수 - group by절, having절 (0) | 2021.12.23 |