177. Nth Highest Salary
https://leetcode.com/problems/nth-highest-salary/
Nth Highest Salary - LeetCode
Can you solve this real interview question? Nth Highest Salary - Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id is the primary key column for this table. Each row
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번째 높은 월급 출력하기
정답
CREATE FUNCTION getNthHighestSalary(n INT) RETURNS INT
BEGIN
SET n = n-1;
RETURN (
SELECT DISTINCT(salary)
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET N -- OFFSET N번째 부터 LIMIT 1개 출력
);
END
SET 함수 사용해서 변수 만들어주기
SET에 n = n-1 변수 입력
salary를 내림차순(DESC)로 해서 높은순으로 정렬
OFFSET
몇번째부터 출력할건지 정해주는 함수.
0으로 하면 첫번째 행부터 나온다. (python처럼 0부터 시작함)
ex) LIMIT 2 OFFSET 0; -- 처음 두 행만 출력
그러니 N에 2가 입력되면
LIMIT 1 OFFSET 1으로 두번째 줄부터 1줄만 출력됨
댓글