简体   繁体   English

使用dense_rank在MYSQL中找到第二高的薪水

[英]Using dense_rank to find the 2nd highest salary in MYSQL

I am trying to do this Leetcode question where we try to find the 2nd highest salary from the EMPLOYEE TABLE.我正在尝试做这个 Leetcode 问题,我们试图从 EMPLOYEE TABLE 中找到第二高的薪水。

INPUT:输入:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+

id is the primary key column for this table. id 是该表的主键列。 Each row of this table contains information about the salary of an employee.此表的每一行都包含有关员工工资的信息。

My answer is the following.我的回答如下。 But leetcode is not accepting this answer.但是 leetcode 不接受这个答案。 What if I don't want to use the offset clause and use the dense function?如果我不想使用偏移子句并使用密集的 function 怎么办? Can it be done?可以做到吗? Kindly help.请帮忙。

with temp1 as
(select id, salary, dense_rank() over (order by salary desc) as salary_order
from employee)
select coalesce(salary, null) as SecondHighestSalary
from temp1
where salary_order=2;

Question Link: https://leetcode.com/problems/second-highest-salary/问题链接: https://leetcode.com/problems/second-highest-salary/

DENSE_RANK() is fine for this problem, but if you filter the cte and there is no 2nd highest salary, the query will not return null . DENSE_RANK()可以解决这个问题,但是如果您过滤 cte 并且没有第二高的薪水,查询将不会返回null
Also, coalesce(salary, null) would just return null if salary is already null , so it does not help.此外,如果salary已经是null ,则coalesce(salary, null)只会返回null ,所以它没有帮助。

With conditional aggregation you can get the 2nd highest salary and null if it does not exist:使用条件聚合,您可以获得第二高的薪水和null如果不存在):

WITH cte AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_order FROM employee)
SELECT MAX(CASE WHEN salary_order = 2 THEN salary END) AS SecondHighestSalary
FROM cte;

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM