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
'Data & BI > SQL Coding Test' 카테고리의 다른 글
[LeetCode](초급) 183. Customers Who Never Order (1) | 2025.05.16 |
---|---|
[LeetCode](초급) 182. Duplicate Emails (0) | 2025.05.16 |
[LeetCode](초급) 175.Combine Two Tables (0) | 2025.05.16 |