从重复值中找出第二高

时间:2018-08-10 23:34:36

标签: sql sql-server

我正在尝试从表中找到第二高薪水的人,该人有多名薪水相同的员工。

 create tablesals (emp_name varchar(10), emp_id INTEGER, salary INTEGER);

insert into sals values ('rr',12,100000);
insert into sals values ('ed',13,100000);
insert into sals values ('ty',14,100000);
insert into sals values ('we',15,80000);
insert into sals values ('wse',16,80000);
insert into sals values ('wa',17,74000);


sel  emp_name,emp_id,salary, ROW_NUMBER() over (order by salary desc) as rrnk from (sel emp_name,emp_id,salary, ROW_NUMBER() over (partition by salary order by salary desc) as rnk
from edwdev.sals) x where x.rnk = 2 and rrnk = 2;

上面是我想出的查询,但是我无法获取正确的数据。 我必须在查询中进行哪些更改。

1 个答案:

答案 0 :(得分:1)

也许dense_rank()会做什么?

SELECT emp_name,
       emp_id,
       salary
       FROM (SELECT emp_name,
                    emp_id,
                    salary,
                    dense_rank() OVER (ORDER BY salary DESC) dr
                    FROM sals) x
       WHERE dr = 2;