본문 바로가기
코딩연습/오라클

[SQL]집합연산자(합집합(union),교집합(intersect),차집합(minus))

by 호아니 2020. 9. 10.
--1. set operator를 이용하여 사원이 없는 부서를 출력
select department_id from departments
minus
select department_id from employees;

--2. set operator를 이용하여 job ID가 ST_CLERK을 포함하지 않는 부서의 ID를 출력
select department_id from departments
minus
select department_id from employees
where  job_id = 'ST_CLERK';

--3. set operator를 이용하여 부서가 없는 지역의 country_id와 country_name을 출력
select country_id, country_name
from   countries
where  country_id in (select country_id
                     from   countries
                     minus
                     select country_id
                     from   departments d inner join locations l
                     on     d.location_id = l.location_id);

--4. 입사후 현재 업무와 같은 업무를 담당한 적이 있는 사원의 employee_id와 job_id를 출력

    ---------------------
  --  EMPLOYEE_ID  JOB_ID 
    ---------------------
 --   176          SA_REP 
 --   200          AD_ASST 
    ---------------------
 select employee_id, job_id
 from   employees
 intersect
 select employee_id, job_id
 from   job_history;
 
--5. 부서번호 10, 50 그리고 20의 순서로 부서의 업무리스트를 정렬 후
--set operators를 이용하여 job_id와 department_id 를 출력.
--column 컬럼이름 noprint를 이용하여 컬럼 출력을 감출 수 있음.
    -----------------------
    --JOB_ID  DEPARTMENT_ID 
    -----------------------
    --AD_ASST            10 
    --ST_CLERK           50 
    --ST_MAN             50 
    --MK_MAN             20 
    --MK_REP             20 
    -----------------------
--column myorder noprint	-- sqlplus에서만 수행 됨.
select job_id, department_id, 1 as myorder from employees
where  department_id = 10
union    
select job_id, department_id, 2 from employees
where  department_id = 50
union  
select job_id, department_id, 3 from employees
where  department_id = 20
order  by 3;