/////
Search
Duplicate

Top Earners

태그
GROUP BY
서브쿼리
한 번 더 체크

문제

We define an employee's total earnings to be their monthly  worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as  space-separated integers.
Input Format
The Employee table containing employee data for a company is described as follows:
where employee_id is an employee's ID number, name is their name, months is the total number of months they've been working for the company, and salary is the their monthly salary.

예시

Sample Input
Sample Output
69952 1
SQL
복사

정답

1.
SELECT MAX(earnings), COUNT(*) FROM( SELECT *, months*salary as earnings FROM Employee ) TEMP WHERE earnings = (SELECT months*salary earnings FROM Employee ORDER BY earnings DESC LIMIT 1)
SQL
복사
2.
SELECT months*salary as earnings, COUNT(*) FROM Employee GROUP BY 1 ORDER BY earnings DESC LIMIT 1;
SQL
복사

풀이

1.
첫 번째 풀이는 FROM 절과 WHERE 절에 서브쿼리를 활용하는 것이다.
우선 FROM절에 서브쿼리를 활용하여 earnings라는 필드를 새로 만든다.
FROM( SELECT *, months*salary as earnings FROM Employee ) TEMP
SQL
복사
그 다음 earnings가 최대인 값들만을 찾아야 하므로 WHERE 절에서 서브쿼리를 활용하여 earnings가 최대인 값들을 찾는다.
WHERE earnings = (SELECT months*salary earnings FROM Employee ORDER BY earnings DESC LIMIT 1)
SQL
복사
→ 나는 이때 earnings를 기준으로 내림차순하여 첫 번째 값이 최댓값인 것을 이용하였다.
마지막으로 MAX(earnings)와 COUNT(*)를 통해 문제에서 찾고자 하는 값을 구하였다.
SELECT MAX(earnings), COUNT(*) FROM( SELECT *, months*salary as earnings FROM Employee ) TEMP WHERE earnings = (SELECT months*salary earnings FROM Employee ORDER BY earnings DESC LIMIT 1)
SQL
복사
2.
두 번째 풀이는 SELECT 절에 earnings를 정의하고 이를 group by 해서 푸는 방식이다.
GROUP BY 절 뒤에 정수가 나오는 경우 SELECT 절의 해당 순번의 필드를 기준으로 그룹핑을 하겠다는 뜻이다. 예를 들어
SELECT months*salary as earnings ... GROUP BY 1
SQL
복사
→ earnings를 기준으로 group by를 수행하겠다는 뜻.
Earnings를 기준으로 group by를 하면 최댓값을 가진 데이터들도 하나로 묶일 것이다. 이때 earnings를 기준으로 내림차순 해주고 COUNT(*)를 통해 각 earning들의 숫자를 세주면 각 earning들과 그 earning을 버는 사람들의 수가 나올 것이다. 이때 우리는 최댓값만 구하면 되므로 LIMIT 1로 제한해주면 된다.
ORDER BY earnings DESC LIMIT 1;
SQL
복사