| comments | true | |
|---|---|---|
| difficulty | 中等 | |
| edit_url | https://github.com/doocs/leetcode/edit/main/solution/0100-0199/0177.Nth%20Highest%20Salary/README.md | |
| tags |
|
表: Employee
+-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | int | +-------------+------+ id 是该表的主键(列中的值互不相同)。 该表的每一行都包含有关员工工资的信息。
编写一个解决方案查询 Employee 表中第 n 高的 不同 工资。如果少于 n 个不同工资,查询结果应该为 null 。
查询结果格式如下所示。
示例 1:
输入: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ n = 2 输出: +------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
示例 2:
输入: Employee 表: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ n = 2 输出: +------------------------+ | getNthHighestSalary(2) | +------------------------+ | null | +------------------------+
我们可以先对 salary 进行降序排序,然后使用 LIMIT 语句获取第
import pandas as pd
def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame:
if N < 1:
return pd.DataFrame({"getNthHighestSalary(" + str(N) + ")": [None]})
unique_salaries = employee.salary.unique()
if len(unique_salaries) < N:
return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"])
else:
salary = sorted(unique_salaries, reverse=True)[N - 1]
return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"])CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N - 1;
RETURN (
# Write your MySQL query statement below.
SELECT (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET N
)
);
END