SQL

[HackerRank SQL] Top Earners

dontgive 2024. 1. 21. 16:02
728x90

https://www.hackerrank.com/challenges/earnings-of-employees/problem?h_r=internal-search&isFullScreen=true

 

Top Earners | HackerRank

Find the maximum amount of money earned by any employee, as well as the number of top earners (people who have earned this amount).

www.hackerrank.com

 

문제 요약

employee_id

name

months

salary

 

네 개의 속성으로 이루어진 Employee라는 테이블이 존재하는데,

 

earnings = months x salary 로 정의한 상황에서

 

(가장 높은 earnings 값) (가장 높은 earnings 값을 가진 사람의 수)

 

를 출력하는 문제이다.

 

해결 전략

total_earnings가 같은 사람들이 존재할 수 있을까? 그럴 수도 있기 때문에 total_earnings를 Alias로 naming하여 조회 하는 동시에 total_earnings 기준으로 GROUP BY를 해준다. 

 

이후 GROUP 내에서 해당하는 사람의 수를 COUNT하고 가장 total_earnings가 높은 그룹만 출력되도록 하는 1번 방법과 GROUP BY한 테이블에서 total_earnings가 가장 큰 값과 일치하는 그룹만 가져온 후에 COUNT로 집계하는 2번 방법이 있다.

 

1. Subquery를 사용하는 방법

-- Solution 1 : without Subquery
SELECT months * salary AS total_earnings
    , COUNT(*) AS nums
FROM Employee
GROUP BY total_earnings
ORDER BY total_earnings DESC
LIMIT 1

 

2. Subquery를 사용하지 않는 방법

-- Solution 2 : with Subquery
SELECT months * salary AS total_earnings
    , COUNT(*) AS nums
FROM Employee
GROUP BY total_earnings
HAVING total_earnings = (SELECT MAX(months * salary) FROM Employee)

 

728x90

'SQL' 카테고리의 다른 글

[JOIN] LEFT JOIN 효과적으로 사용하기  (0) 2024.02.18
DISTINCT 대신 GROUP BY?  (1) 2024.02.10
[HackerRankSQL] Symmetric Pairs  (0) 2024.02.02
[HackerRank SQL] The Report 문제풀이  (2) 2024.01.29