简体   繁体   中英

Why is my Nth Highest Salary SQL Query Syntax Wrong?

I know there are a ton of questions about nth highest salary, but I don't get why my syntax is wrong. Compilers show that there's an error at the N-1); part but I don't see why that's wrong. Thanks!

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT 1, OFFSET N-1
  );
END

I am going to ignore the fact that depending on your data, the query as you've written it, may not return the results you expect. Instead, I'll focus on fixing the syntax errors:

  1. You need to redefine the default semi colon ( ; ) delimiter to something else so that the semi colon inside the function body doesn't get misinterpreted. (Maybe you're doing that already, but since you're not showing it, I mention it in case)
  2. There shouldn't be a comma separating LIMIT and OFFSET
  3. MySQL seems to expect a single value as the OFFSET parameter. It doesn't seem to like a calculated expression the way you have it. In that case, you just need to calculate the desired value before using it in the SQL statement.

Applying the above, here is what it would look like:

delimiter //
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  SET N = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET N
  );
END
//

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM