Nth Highest Salary --- 找出第N高的工资

Q:

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

Nth Highest Salary --- 找出第N高的工资_第1张图片

For example, given the above Employee table, the Nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

找出第n高的工资,若不存在则返回空值。


A:

该题不容易想出答案,但是SQL中的一个命令可以很简单的解决这个问题

select * from table limit m,n

上面的语句表示从table表中查询从m+1开始的n条记录

所以该问题可以用下面的查询语句来解决

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      select distinct Salary 
      from Employee
      order by Salary desc limit N,1
  );
END
先将数据按工资从高到低进行排序,然后输出其中的第N条即可


总结:

这题如果不知道有limit这个方法的话还是挺不容易解决的,所以平时也要多看看数据库相关资料,将一些常用的、出现频率较高的语法掌握扎实,这样做起题来才会更加的顺手。

你可能感兴趣的:(leetcode)