第二高的薪水:
描述
查询并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null(Pandas 则返回 None)
pandas
import pandas as pddef second_highest_salary(employee: pd.DataFrame):# 1. 删除所有重复的薪水.employee = employee.drop_duplicates(["salary"])# 2. 如果少于 2 个不同的薪水,返回 `np.NaN`。if len(employee["salary"].unique()) < 2:return pd.DataFrame({"SecondHighestSalary": [np.NaN]})# 3. 把表格按 `salary` 降序排序。employee = employee.sort_values("salary", ascending=False)# 4. 删除 `id` 列。employee.drop("id", axis=1, inplace=True)# 5. 重命名 `salary` 列。employee.rename({"salary": "第二高"}, axis=1, inplace=True)# 6. 返回第 2 高的薪水return employee.head(2).tail(1)
SQL
方法一
SELECTIFNULL((SELECT DISTINCT SalaryFROM EmployeeORDER BY Salary DESCLIMIT 1 OFFSET 1),NULL) AS SecondHighestSalary
方法二
select max(salary) as SecondHighestSalary
from Employee
where salary < (select max(salary) from Employee);