Database/SQL Server

SQL Server - 릿코드 데이터베이스 문제 177. Nth Highest Salary // Leetcode Database Problem

청렴결백한 만능 재주꾼 2022. 7. 27. 04:05
반응형

177. Nth Highest Salary

 

테이블 정보 출처 : Leetcode.com

이번에도 하나의 테이블이 주어진다.

 

 

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.
n번째로 높은 샐러리를 뽑는 SQL 쿼리를 작성하시오. 만약 n번째 높은 샐러리가 없다면 null값을 리턴하시오.

 

예시,

예시 출처 : Leetcode.com

 


풀이,

Input Parameter가 있으니 Function으로 만들어야 한다. 틀은 이미 주어져 있다. 

CREATE FUNCTION getNthHighestSalary(@N INT) RETURNS INT AS
BEGIN
    RETURN (
        /* Write your T-SQL query statement below. */
    );
END

 

중복된 샐러리가 있으면 어떻게 하지. 뭐 이런 순서에 관한 문제들은 Rank(), Dense_Rank(), Row_Number()로 대부분 처리 된다. row_number로 해본다.

CREATE FUNCTION getNthHighestSalary(@N INT) RETURNS INT AS
BEGIN
    RETURN (
        /* Write your T-SQL query statement below. */
        select top 1 (em.salary) salary
          from (select row_number() OVER (ORDER BY salary desc) no,
                       salary
                  from Employee
                 where salary is not null
                group by salary
                 union all
                select null, null) em
         where em.no = @N  or em.no is null
         order by em.salary desc
    );
END

결과 출처 : Leetcode.com

되었다. 

반응형