배우기/SQL

HackerRank - Top Earners (서브쿼리 / GROUP BY 외)_MySQL

인사잘해 2022. 4. 8. 16:14

안녕하세요!

 

Employee 테이블에 있는 employee_id, name, months, salary 컬럼을 통해

수입이 가장 높은 직원이 몇 명인지 알아보는 문제입니다.

 

테이블 설명
months : 근무기간 / salary : 월급

 

3가지 방법으로 결과를 출력해봤습니다.

 

1) where 절 서브쿼리

where 절에는 select 절의 alias를 사용하지 못하기 때문에 컬럼명을 그대로 사용했습니다.

count 에는 * 를 사용해도 결과는 같습니다.

select months * salary total_earning, count(employee_id)
from employee
where months * salary >= (select max(months * salary) from employee)
group by 1

2) having 절 서브쿼리

having절은 select 절 alias를 사용할 수 있습니다. (group by, order by 절에도 가능합니다.)

select months * salary total_earning, count(*)
from employee
group by 1
having total_earning >= (select max(months * salary) from employee)

3) group by-order by-limit

서브쿼리를 사용하지 않은 풀이입니다.

select months * salary total_earning, count(*)
from employee
group by 1
order by total_earning desc
limit 1

4) where

where 조건을 사용한 풀이입니다.

select months*salary as total_earning, count(*)
from employee
where months*salary = (select max(months*salary) from employee)
group by 1

출처 : https://www.hackerrank.com/challenges/earnings-of-employees/problem