[Oracle SQL] 조인 연습 문제 풀이 (3)

yoonheekim·2022년 11월 4일
0

Oracle SQL

목록 보기
9/15

📚 Join - hr

1. 각 직책 별(job_title)로 급여의 총합을 구하되 직책이 Representative 인 사람은 제외하십시오. 단, 급여 총합이 30000 초과인 직책만 나타내며, 급여 총합에 대한 오름차순으로 정렬하십시오. 출력 결과의 컬럼명은 아래 결과와 동일하게 주십시오.

select j.job_title as job, sum(e.salary) as 급여
from jobs j, employees e
where j.job_id=e.job_id
and j.job_title not like '%Reprsentative'
group by job_title
having sum(e.salary)>3000
order by 급여;

✏️ 쿼리문의 실행순서를 고려해야 했던 문제! 쿼리문 실행 순서는 다음과 같다.
From->Connect by->Where->Group by->Having->Select->Order by
Select문이 실행되면서 만들어진 별칭은 Orderby문에서 사용할 수 있지만 Select문이이 실행되기 전 단계들에서는 별칭 사용이 불가능하다.

2. 각 부서 이름 별로 2005년 이전에 입사한 직원들의 인원수를 조회하시오.

select d.department_name as 부서명, count(e.employee_id) as 인원수
from employees e, departments d
where e.department_id=d.department_id
and e.hire_date < '01-jan-05'
group by d.department_name; 

3. 사원수가 3명 이상의 사원을 포함하고 있는 부서의 부서번호(department_id), 부서이름(department_name), 사원 수, 최고급여, 최저급여, 평균급여, 급여총액을 조회하여 출력하십시오. 출력 결과는 부서에 속한 사원의 수가 많은 순서로 출력하고, 컬럼명은 아래 결과와 동일하게 출력하십시오. (평균급여 계산시 소수점 이하는 버리시오)

나의 코드 : 
select e.department_id as 부서번호
d.department_name as 부서명
count(e.employee_id) as 인원수
j.max_salary as 최고급여
j.min_salary as 최소급여
trunc(avg(e.salary)) as 평균급여
sum(e.salary)  as 급여총액
from employees e, departments d, jobs j
where e.department_id=d.department_id
and e.job_id=j.job_id
group by d.department_name
having count(e.employee_id) >= 3
order by 인원수 decs;

수정한 코드 : 
select e.department_id 부서번호,
d.department_name 부서명,
count(e.employee_id) 인원수,
max(e.salary) 최고급여,
min(e.salary) 최저급여,
trunc(avg(e.salary),0) 평균급여,
sum(e.salary) 급여총액
from employees e, departments d
where e.department_id = d.department_id
group by e.department_id,d.department_name
having count(e.employee_id)>=3
order by 인원수 desc;

✏️ 틀린 이유1) 최고급여와 최저금여를 구할 때 조건이 '부서' 였는데 jobs의 max_salary, min_salary를 사용하였음.
✏️ 틀린 이유2) 문제의 조건이 부서번호, 부서이름 별로 사원수,급여를 출력하는 것이기 때문에 group by절에 부서의 id, 부서의 name을 명시하여야 했어야 한다.
✏️ 틀린 이유3) 오타...😂 order by절에서 내림차수로 정렬하는 명령어 'desc'를 'decs'로 적음 하하하
✏️ 틀린 이유4) select 문에서 콤마(,)를 안썼다!

💡느낀점

나는 분명히 충분히 분석을 하고 코드를 짠 것 같은데 내 코드는 왜 실행이 안되는걸까...?

왜긴 왜야 잘못 분석했으니까 그렇지...😂

profile
개발 걸음마 떼기 👩🏻‍💻

0개의 댓글