Data & BI/SQL Coding Test

[LeetCode](중급) 176. Second Highest Salary

무료한하늘 2025. 5. 16. 14:12
728x90

문제

Column Name Type
id int
salary int
[Table : Employee]
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.

 

Write a solution to find the second highest distinct salary from the Employee table. If there is no second highest salary, return null

 

주어진 Employee 테이블에서 두 번째로 높은 급여를 조회해라. 두 번째 급여가 없다면 null을 조회해라.

 

풀이

SELECT COALESCE(
    (
        SELECT DISTINCT(salary)
        FROM Employee
        ORDER BY salary DESC
        OFFSET 1 ROWS			-- 1개 행 건너뛰기
        FETCH NEXT 1 ROWS ONLY	-- 건너 뛴 행에서 한 개만 조회
    ), null
) as SecondHighestSalary

 

두 번째 급여를 조회하기 위해 ORDER BY 를 통해 급여를 내림차순으로 정렬하고, OFFSET...FETCH 로 한 행 건너뛰어서 하나의 행만 조회되도록 쿼리했다.

 

만약, 없다면 null 을 조회하기 위해 COALESCE 함수를 이용해 null을 반환하도록 하였다.

300x250