본문 바로가기

MySQL

[leetcode] [MySQL] 176. Second Highest Salary

 

https://leetcode.com/problems/second-highest-salary/submissions/

 

Second Highest Salary - LeetCode

Second Highest Salary - Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key column for this table. Each row of this table contains information about

leetcode.com

problem

Write an SQL query to report the second highest salary from the Employee table. If there is no second highest salary, the query should report null.

2번째로 높은 salary를 출력하는 문제. 해당하는 salary가 없으면 null을 반환하라 

 

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
Output: 
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
Output: 
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                |
+---------------------+

 

Example 3 : 직접 테스트 추가 ( 가장 높은 salary 가 여러개인 경우를 고려해서 테스트 추가해보았다) 

 

 


solution

이 문제에서 계속 오류난 부분이  2번째로 높은 salary가 존재하지 않으면 null 값이 반환이 안되고 아무것도 출력되지 않는다. 그런데 null 값이 나오도록 해야하므로 계속 틀렸었다. 

그래서 max(salary)로 max 집계함수를 사용하면 값이 없을 경우에  null 값이 나온다.. 

 

처음에 틀린 코드

CASE2 부분에서 null 값이 반환되지 않아 틀림 

WITH salary_ranking AS (
                    SELECT id, salary, rank () over(order by salary DESC) as 'ranking'
                    FROM Employee
)
SELECT IF(ranking is null,'null',salary) as 'SecondHighestSalary' -- 오류 부분-> null값 반환 안됨  
FROM salary_ranking
WHERE ranking = 2

 

 

정답 

[1] with 절 사용 

WITH salary_ranking AS (
                    SELECT id, salary, dense_rank () over(order by salary DESC) as 'ranking' -- dense_rank 사용 
                    FROM Employee
)
SELECT IF(max(ranking)=2,salary,null) as 'SecondHighestSalary' 
FROM salary_ranking
WHERE ranking = 2
-- Runtime :443 ms

[2] 서브쿼리 사용

SELECT IF(max(R.ranking)=2,R.salary,null) as 'SecondHighestSalary' 
FROM (
       SELECT salary
            , dense_rank() over(order by salary DESC) as "ranking" 
       FROM Employee
       ) R -- From 절 서브쿼리 쓸 때 별칭 사용해야함 
WHERE R.ranking = 2
--350 ms

[3] ifnull + 서브쿼리 사용

[3] ifnull, subquery 사용 

SELECT IFnull(max(R.salary),null) as 'SecondHighestSalary' -- 오류 부분-> null값 반환 안됨  
FROM (
       SELECT salary
            , dense_rank() over(order by salary DESC) as "ranking" 
       FROM Employee
       ) R
WHERE R.ranking = 2
--Runtime 374 ms

 


다른 사람 풀이 

이렇게 간단하게 풀 수 있다니..! 

출처: https://wakestand.tistory.com/293

SELECT MAX(SALARY) AS SecondHighestSalary
  FROM EMPLOYEE
 WHERE SALARY NOT IN(SELECT MAX(SALARY) FROM EMPLOYEE)
 -- 최대값 제외하고 차순위 값이 2위, 없을 경우에는 NULL