Leetcode 177 Nth Highest Salary SQL Pandas解法

177. Nth Highest Salary SQL Pandas解法

  • 题目
  • 解法
    • SQL
      • 解法一:limit offset
      • 解法二:dense_rank
    • Pandas

题目

Easy

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

Id Salary
1 100
2 200
3 300

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.

getNthHighestSalary(2)
200

解法

这道题和176本质是一样的,思路请移步这里。这道题需要我们写成一个function来解决此类问题。

  • 首先我们定义一个变量,M = N - 1,写在最前面,主要是因为选择第N个数值,需要offset N-1个数值
  • 其次使用limit offset来选取第N个数值

SQL

解法一:limit offset

使用function之前的LC 176的解法是这样的

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

定义function之后是这样的

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN

declare M int;
set M = N-1;

  RETURN (
      # Write your MySQL query statement below.
      select 
      ifnull(
          (
          select distinct salary 
          from Employee
          order by salary desc
          limit 1
          offset M), 
      NULL)
  );
END

解法二:dense_rank

  • 首先对salary进行降序排序,无间隔
  • 选取序列号为N的数值,并且返回该salary值
CREATE FUNCTION getNthHighestSalary(@N INT) RETURNS INT AS
BEGIN
    RETURN (
        /* Write your T-SQL query statement below. */
        select t.salary 
        from 
        (select distinct salary, 
                dense_rank() over (order by salary desc) as rnk
            from employee as e
        ) as t
        where t.rnk = @N
    );
END

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]})

import numpy as np

def getNthHighestSalary(salary, N) -> int:
  salary = np.unique(salary)
  salary = sorted(salary)  
  return salary[-N]

df[['Salary']].apply(lambda x: getNthHighestSalary(x, 2))

你可能感兴趣的:(Leetcode,Database,SQL/Pandas)