如何获得第二高价值?

时间:2018-02-11 01:56:12

标签: sql oracle

假设我有下表:

   employee_id    salary
   22             49
   19             49

我想要返回薪水第二高的员工(当有关系时),如下:

{{1}}

我该怎么做?

4 个答案:

答案 0 :(得分:2)

使用DENSE_RANK

SELECT employee_id, salary
FROM
(
    SELECT employee_id, salary, DENSE_RANK() OVER (ORDER BY salary DESC) dr
    FROM yourTable
) t
WHERE dr = 2;

答案 1 :(得分:0)

您可以使用嵌套查询。

采取的步骤:

  1. 获取所有工资值(对其进行排序并获得第二高的值):
  2. SELECT salary FROM employee GROUP BY 1 ORDER BY 1 DESC limit 1 OFFSET 1;

    OR可以写成:

    SELECT salary FROM employee GROUP BY employee_id ORDER BY employee_id DESC limit 1 OFFSET 1;
    

    现在使用员工表中的查询

    SELECT * FROM employee where salary=(SELECT salary FROM employee GROUP BY 1 ORDER BY 1 DESC limit 1 OFFSET 1);

答案 2 :(得分:0)

这也可以使用下面的查询来完成,

方案1:输出两条记录

WITH employee
AS (
SELECT 34 emp_id, 100 rate FROM DUAL
UNION
SELECT 22 emp_id, 49 rate FROM DUAL
UNION
SELECT 19 emp_id, 49 rate FROM DUAL
UNION
SELECT 29 emp_id, 30 rate FROM DUAL
UNION
SELECT 17 emp_id, 22 rate FROM DUAL),
emp_rate_cnt AS 
(SELECT rownum rown, rate, same_rate_count
   FROM (SELECT rate, count(1) same_rate_count
           FROM employee
          GROUP BY rate
          ORDER BY rate DESC))
SELECT *
  FROM employee a
 WHERE exists (SELECT 1
                 FROM emp_rate_cnt b
                WHERE b.rate = a.rate
                  AND b.rown = 2
                  AND b.same_rate_count > 1);

方案2:输出无记录

WITH employee
AS (
SELECT 34 emp_id, 100 rate FROM DUAL
UNION
SELECT 22 emp_id, 49 rate FROM DUAL
UNION
SELECT 19 emp_id, 50 rate FROM DUAL
UNION
SELECT 29 emp_id, 30 rate FROM DUAL
UNION
SELECT 17 emp_id, 22 rate FROM DUAL),
emp_rate_cnt AS 
(SELECT rownum rown, rate, same_rate_count
   FROM (SELECT rate, count(1) same_rate_count
           FROM employee
          GROUP BY rate
          ORDER BY rate DESC))
SELECT *
  FROM employee a
 WHERE exists (SELECT 1
                 FROM emp_rate_cnt b
                WHERE b.rate = a.rate
                  AND b.rown = 2
                  AND b.same_rate_count > 1);

答案 3 :(得分:0)

我希望这是最简单的。使用rownum,因为它是Oracle。

SELECT t.employee_id, t.salary
FROM
(
    SELECT distinct employee_id, salary, rownum as row from 
    FROM yourTable order by salary desc
) t
WHERE t.row = 2;