SQL/LeetCode

[177] Nth Highest Salary

소금깨 2022. 6. 3. 22:54

1. 문제 설명

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 the salary of an employee.

 

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

The query result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+

2. 문제 풀이

- 사용자 정의 함수를 써야하는데, n번째 highest salary를 가진 사람을 찾아 출력해야하는 상황.- 만약 해당되는 n번째 salary의 값이 없는 경우, NULL을 출력해야 한다. 

 

함수를 사용하지 않고 어떻게 N번째 값을 구할 수 있을까?

 

# 사용자 정의 함수를 사용하지 않을 때 
select case when count(sub.salary < N then null 
			else min(sub.salary) 
            end
from (select distinct salary
        from employee
        order by salary desc
        limit n) sub
# 사용자 함수 써서 작성하기

CREATE FUNCTION getNthHighestSalary (N INT)
RETURNS INT
BEGIN 	
	RETURN (
    		SELECT CASE WHEN COUNT(sub.Salary) < N THEN NULL
            			ELSE MIN(sub.Salary)
                	END
            FROM ( SELECT DISTINCT Salary 
            		FROM Employee
                    ORDER BY Salary DESC
                    LIMIT N
                    ) sub
     ); 
END

3. 결과