Programming/SQL

[SQL/실습] 서브쿼리와 함수를 조합하여 문제풀기

reeme 2020. 12. 17. 22:55

sql example.xlsx
0.01MB

서브쿼리와 함수를 조합하여 풀기

select*from employee;
select * from department;

-- 1. 사원명 'e3'가 속한 부서명을 조회하시오
-- 부서명을 알기위해서는 e3의 부서번호가 필요함
-- select 부서번호 from 사원테이블 where 사원명='e3';
-- select 부서명 from 부서테이블 where 부서번호 = (e3이라는 사원명의 부서번호 )

select dno 
from employee
where ename='e3';
select dname
from department
where dno=(select dno 
from employee
where ename='e3')
;
select * from employee;

 


-- 2. 평균 월급보다 더 많은 월급을 받은 사원의 사원번호 / 이름 / 월급을 조회하시오
-- select 사원번호, 이름, 월급 from 사원테이블 where 개인월급 > 평균월급 

select eno, ename,salary
from employee
where salary >(select avg(salary) from employee);

 

-- IN / ANY / ALL 은 뒤에 몇개인지에 따라서 다중(둘이상)이면 써줘야함 
-- 만약 group by를 넣으려면 ? any/in/all없이는 실행이 안됨 왜냐면 값이 다중이라 

select eno, ename,salary
from employee
where salary > all (select avg(salary) from employee GROUP BY DNO);

 

-- in은 같은것에 대해서만 비교할 수 있음 크다작다는 안됨

select eno, ename,salary
from employee
where salary > (select avg(salary) from employee GROUP BY DNO having dno='20');

 

-- 이렇게 having으로 조건주고 all뺄 수도 있음

 


-- 3. 부서번호가 10인 사원들 중에서 최대급여를 받는 사원과 
-- 동일한 급여를 받는 사원의 사원번호와 이름을 조회하시오.

select eno,ename
from employee
where salary = (select max(salary) from employee where dno = '10'); 

 

-- 부서번호가 10인 사원중에서 최대급여를 받는 사원

select max(salary) from employee where dno = '10';