diff --git a/README.md b/README.md index 619adf2..2d71b98 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ Useful for preparing for technical interviews and improving your SQL skills. - [3570. Find Books with No Available Copies](./leetcode/easy/3570.%20Find%20Books%20with%20No%20Available%20Copies.sql) 2. [Medium](./leetcode/medium/) - [176. Second Highest Salary](./leetcode/medium/176.%20Second%20Highest%20Salary.sql) + - [177. Nth Highest Salary](./leetcode/medium/177.%20Nth%20Highest%20Salary.sql) - [180. Consecutive Numbers](./leetcode/medium/180.%20Consecutive%20Numbers.sql) - [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql) - [550. Game Play Analysis IV](./leetcode/medium/550.%20Game%20Play%20Analysis%20IV.sql) diff --git a/leetcode/medium/177. Nth Highest Salary.sql b/leetcode/medium/177. Nth Highest Salary.sql new file mode 100644 index 0000000..220cdd2 --- /dev/null +++ b/leetcode/medium/177. Nth Highest Salary.sql @@ -0,0 +1,35 @@ +/* +Question 177. Nth Highest Salary +Link: https://leetcode.com/problems/nth-highest-salary/description/?envType=problem-list-v2&envId=database + +Table: Employee + ++-------------+------+ +| Column Name | Type | ++-------------+------+ +| id | int | +| salary | int | ++-------------+------+ +id is the primary key (column with unique values) for this table. +Each row of this table contains information about the salary of an employee. + + +Write a solution to find the nth highest distinct salary from the Employee table. If there are less than n distinct salaries, return null. +*/ + +CREATE OR REPLACE FUNCTION NTHHIGHESTSALARY(N INT) RETURNS TABLE (Salary INT) AS $$ --noqa: CP03 (function NthHighestSalary) +BEGIN + IF N <= 0 THEN + Salary := NULL; + RETURN NEXT; + RETURN; + END IF; + + RETURN QUERY ( + SELECT DISTINCT e.salary + FROM Employee e + ORDER BY e.salary DESC + LIMIT 1 OFFSET (N - 1) + ); +END; +$$ LANGUAGE plpgsql;