Leetcode Nth Highest Salary

Source: Internet
Author: User

Write a SQL query to get the nth highest salary from the Employee table.

+----+--------+| Id | Salary |+----+--------+| 1 | |    | 2 | | |    3  |    |+----+--------+

For example, given the above Employee table, theNthHighest salary whereN= 2 is200. If there is noNthHighest salary, then the query should returnnull.

Note that the same salary is counted as one, and that limit and offset cannot be used in expressions, at least not when I write.

At first do not know how to declare a variable, the result obstinately wrote this method:

CREATE FUNCTION getnthhighestsalary (N INT) RETURNS intbegin  RETURN (select      (select A.salary from (select Distinct b.salary from employee B union ALL select Max (c.salary) from employee C) a order by a.salary desc LIMIT 1 Offset N )  ); END
Later, in discuss, I saw how to declare a variable:

CREATE FUNCTION getnthhighestsalary (N INT) RETURNS intbegindeclare m Int;set m = N-1;  RETURN (      select distinct salary from Employee order by salary desc LIMIT 1 offset M  ); END

Leetcode Nth Highest Salary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.