Leetcode 176 Second Highest Salary SQL Pandas解法

176. Second Highest Salary SQL Pandas解法

题目

Easy

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

IdSalary
1100
2200
3300

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

SecondHighestSalary
200

解法

解答这道题需要考虑两点:1)第二高的工资是否存在;2)如果存在,结果会不会存在并列的情况。这里我们用limitoffset 来寻找第二高的工资。

  • offset k 会将前k行跳过
  • limit j 限定返回结果中的前j

这里先去重(distinct),降序排序,再从结果中从第二行开始选择第一个结果。如果结果不存在,将结果设置为null

SQL

解法一

select (
  select distinct salary 
  from employee
  order by Salary DESC
  limit 1
  offset 1) as SecondHighestSalary

解法二

select ifnull(
(
  select distinct salary from employee
  limit 1 offset 1
)
, NULL) as SecondHighestSalary

解法三

select ifnull(max(Salary), NULL) as SecondHighestSalary
from Employee
where Salary not in (select max(Salary) as maxSalary from Employee)

Pandas

  • 建立Salary表
  • 降序排列Salary列
  • 使用dense rank计算排序,意味着数值并列时,排名相同,并且连续。例如,5,5,4,3,3的排序为1,1,2,3,3
  • 选取排序为2的,并且将列重命名为 SecondHighestSalary
import pandas as pd
# create pandas data frame
df = pd.DataFrame({'ID': [1,2,3,4,5,6], 'Salary': [100, 200, 300, 300, 200, 200]})
# sort by descending
df[df.Salary != df.Salary.max()].sort_values(by = 'Salary', ascending = False)
# create dense rank
df['Rank'] = df.Salary.rank(method='dense').astype('int')
# subset and rename 
df[df.Rank == 2]['Salary'].to_frame().rename(columns={'Salary':'SecondHighestSalary'}).drop_duplicates().reset_index(drop=True)

简单方法,一步到位 😃

df.Salary.nlargest(2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值