techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

Leetcode | 第二高的薪水/第N高的薪水 #10

Open techiall opened 6 years ago

techiall commented 6 years ago

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

第二高薪水还是第N高薪水,原理类似。注意一些细节。

使用子查询,比较任意的两份薪资,当 薪资 = N - 1 的时候,就是第 N 高薪水。注意使用 count 将薪资相同的聚合在一起(相同薪资的人可能有多个),并去重。

mysql

第二高的薪水

select max(e.Salary) SecondHighestSalary from Employee e

where (select count(distinct e1.Salary)

        from Employee e1 where e1.Salary > e.Salary) = 1

第 N 高的薪水

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT

BEGIN

  RETURN (

      # Write your MySQL query statement below.

      select max(e.Salary) SecondHighestSalary 

      from Employee e 

      where (select count(distinct e1.Salary)

             from Employee e1 

             where e1.Salary > e.Salary) = N - 1

  );

END