王廷瑋|數位醫療|智慧醫療: 176. Second Highest Salary WFU

2024年7月9日 星期二

176. Second Highest Salary

176. Second Highest Salary


表格:Employee

+-------------+------+
 | 列名 | 類型 | 
+-------------+------+ 
| id | int | 
| salary | int |
 +-------------+------+
 id 是此表格的主鍵(具有唯一值的列)。 此表的每一行包含一名員工的薪資信息。

撰寫一個解決方案來從 Employee 表中查找第二高的薪資。如果沒有第二高的薪資,則返回 null(在 Pandas 中返回 None)。

結果格式如下例所示。

範例 :

輸入: Employee 表: 
+----+--------+
 | id | salary | 
+----+--------+ 
| 1 | 100 | 
| 2 | 200 |
 | 3 | 300 | 
+----+--------+

輸出: 
+---------------------+ 
| SecondHighestSalary | 
+---------------------+ 
| 200 | 
+---------------------+


MySQL


# Write your MySQL query statement below
SELECT
IFNULL(
(SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary;

223ms


Pandas


import pandas as pd

def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
unique_salaries = employee['salary'].drop_duplicates().nlargest(2)
if len(unique_salaries) < 2:
return pd.DataFrame({'SecondHighestSalary': [None]})
second_highest = unique_salaries.iloc[-1]
return pd.DataFrame({'SecondHighestSalary': [second_highest]})

67.21MB, 352ms


PostgreSQL


-- Write your PostgreSQL query statement below
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);

0.00MB, 316ms