[177] Nth Highest Salary

2022. 6. 3. 22:54·SQL/LeetCode

1. 문제 설명

Table: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id is the primary key column for this table.
Each row of this table contains information about the salary of an employee.

 

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.

The query result format is in the following example.

 

Example 1:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

Example 2:

Input: 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
Output: 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+

2. 문제 풀이

- 사용자 정의 함수를 써야하는데, n번째 highest salary를 가진 사람을 찾아 출력해야하는 상황.- 만약 해당되는 n번째 salary의 값이 없는 경우, NULL을 출력해야 한다. 

 

함수를 사용하지 않고 어떻게 N번째 값을 구할 수 있을까?

 

# 사용자 정의 함수를 사용하지 않을 때 
select case when count(sub.salary < N then null 
			else min(sub.salary) 
            end
from (select distinct salary
        from employee
        order by salary desc
        limit n) sub
# 사용자 함수 써서 작성하기

CREATE FUNCTION getNthHighestSalary (N INT)
RETURNS INT
BEGIN 	
	RETURN (
    		SELECT CASE WHEN COUNT(sub.Salary) < N THEN NULL
            			ELSE MIN(sub.Salary)
                	END
            FROM ( SELECT DISTINCT Salary 
            		FROM Employee
                    ORDER BY Salary DESC
                    LIMIT N
                    ) sub
     ); 
END

3. 결과 

'SQL > LeetCode' 카테고리의 다른 글

180,184,1075,1076,1082  (0) 2022.06.22
[STUDY_PALN] DAY1  (0) 2022.06.04
[180] Consecutive Numbers  (0) 2022.05.29
[196] Delete Duplicate Emails  (0) 2022.05.28
[185] Department Top Three Salaries  (0) 2022.05.26
'SQL/LeetCode' 카테고리의 다른 글
  • 180,184,1075,1076,1082
  • [STUDY_PALN] DAY1
  • [180] Consecutive Numbers
  • [196] Delete Duplicate Emails
소금깨
소금깨
  • 소금깨
    고군분투 인생살이
    소금깨
  • 전체
    오늘
    어제
    • 분류 전체보기 (328)
      • SQL (271)
        • 프로그래머스 (27)
        • LeetCode (198)
        • Hacker Rank (27)
        • Solve SQL (1)
        • 개념 (15)
      • 데이터 분석 (16)
        • 참고하며 공부하기 (14)
      • 기타 (15)
        • 통계 (14)
      • 오류 (6)
      • 인생살이 (0)
        • 리뷰 (0)
        • 일기 (0)
      • 中文 (0)
      • TABLEAU (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    프리미엄
    직장인자기계발
    파이썬을활용한시계열데이터분석AtoZ올인원패키지Online
    easy
    프로그래머스
    MySQL
    solvesql
    파이썬을활용한시계열데이터분석
    패스트캠퍼스
    시계열데이터분석
    SQL
    Hard
    LeetCode
    HACKER_RANK
    medium
    group by
    해커랭크
    패캠챌린지
    패스트캠퍼스후기
    직장인인강
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
소금깨
[177] Nth Highest Salary
상단으로

티스토리툴바