취미가 좋다
176. Second Highest Salary 본문
https://leetcode.com/problems/second-highest-salary/
Second Highest Salary - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Solution
SELECT Max(Salary) SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT Max(Salary) FROM Employee)
- 서브 쿼리에 미리 제일 큰 수를 구해놓고, 그 다음 큰 수를 찾는다.
SELECT Max(Salary) SecondHighestSalary
FROM Employee
WHERE Salary NOT IN (SELECT Max(Salary) FROM Employee)
- 서브쿼리로 찾은 값과 비교하지 않고, NOT IN으로 그 수를 제외 시키면 더 빠른 런타임으로 동작한다.
select (
select distinct Salary
from Employee
order by Salary Desc
limit 1
offset 1
)as SecondHighestSalary
- offset 을 통해 몇 번째부터 출력할 것인지 선택할 수 있다.
- offset은 limit과 함께 사용한다.
- 2번째 Salary가 없을 때 Null을 입력해야 하므로 select로 한 번 더 감싸준다.
- 가장 높은 Salary가 중복될 때는 제거해야하므로 distinct를 넣어준다.
select (
select distinct Salary
from Employee
order by Salary Desc
limit 1,1
)as SecondHighestSalary
- offset을 limit에서 저렇게 표현할 수 있다.
'SQL 문제풀이 > Leetcode' 카테고리의 다른 글
178. Rank Scores (0) | 2021.09.06 |
---|---|
182. Duplicate Emails (0) | 2021.09.04 |
181. Employees Earning More Than Their Managers (0) | 2021.09.04 |
177. Nth Highest Salary (0) | 2021.08.13 |
175. Combine Two Tables (0) | 2021.08.13 |
Comments