복's

[ LeetCode - 176 ] Second Highest Salary 본문

알고리즘/LeetCode

[ LeetCode - 176 ] Second Highest Salary

나복이 2023. 11. 18. 16:01
728x90

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

 

Second Highest Salary - LeetCode

Can you solve this real interview question? Second Highest Salary - Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key (column with unique values)

leetcode.com

DB는 Medium 까지는 풀어도되지 않을까 싶어서 풀어봤다.

요즘 typeorm만 보다 보니까 쿼리 작성할 일도 없고..(사실 orm, odm도 잘 못씀)

그래도 기본은 작성해야 하지 않을까 싶어서 가끔 한 문제씩 하고 있다.(한 문제에 아직까지는 시간이 오래 안걸려서 딱히 프로젝트에 지장도 없고)


[ 📌 풀이 ]

두 번째 급여가 높은 사람을 구하기 위해서 각 row에 맞는 rank를 매겨줬다.

  • dense_rank()를 통해서 급여별 랭킹 부여

랭킹이 붙은 서브 쿼리에서 랭킹이 2인 사람을 출력했다.

  • MAX 집계 함수를 사용해서 출력을 도왔다. (row가 1줄 밖에 없으면 null이 출력되어야 하기 때문에)

[ 📌 코드 - Oracle ]

-- Author    : Lee In Bok 
-- Date      : 2023.11.18(Sat)
-- Spend Time: 11m 09s
-- Runtime   : 653 ms (Beats 86.13%)
-- Algoritm  : Aggregation, rank

select MAX(salary) as SecondHighestSalary
  from (
        select dense_rank() over(order by salary desc) as rank
             , salary
          from Employee
       )
 where rank = 2
;

[ 📌 결과 - Oracle ]

[ Result - Oracle ]

728x90