177. Nth Highest Salary

 

Nth Highest Salary

Nth Highest Salary

Problem Description

SQL Schema

          Create table If Not Exists Employee (Id int, Salary int)
    Truncate table Employee
    insert into Employee (id, salary) values ('1''100')
    insert into Employee (id, salary) values ('2''200')
    insert into Employee (id, salary) values ('3''300')



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 the highest salary from the Employee table. If there is no nth the 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                   |
+------------------------+

Idea:
Approach 1)
  • The main thing is to study the use of the creative function.
    • Declare variables using declare
    • set variable value

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare M int;
set M = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      select distinct
            Salary
        from
            Employee
        order by
            Salary desc
        limit
            M, 1
  );
END

Approach 2) Two Brushes
  • Mathematical operations cannot be performed on the data after the offset keyword. 
  • That's why we need to assign N - 1 externally.

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M int;
SET M = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT IFNULL(
          (SELECT DISTINCT Salary
          FROM Employee
          ORDER BY Salary DESC LIMIT 1 OFFSET M), NULL) as Salary
  );
END 
sdasd


Conclusion

That’s all folks! In this post, we solved LeetCode problem #177. Nth Highest Salary
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to solve Leetcode questions & present the most important points to consider when improving Data structure and logic,  feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post