如何使用postgresql查询找出员工的第二高薪

时间:2013-07-12 07:01:48

标签: sql postgresql derived-table

创建表名为geosalary,列名称为name,id,salary;

name   id  salary  
patrik  2  1000  
frank   2  2000  
chinmon 3  1300  
paddy  3   1700  

我试过以下代码找到第二高薪

SELECT salary FROM (SELECT salary ,DENSE_RANK() OVER(ORDER BY SALARY) AS DENSE_RANK FROM geosalary) WHERE DENSE_RANK=2;

但是收到以下错误消息,

*** 错误 ** *

ERROR: subquery in FROM must have an alias  
SQL state: 42601  
Hint: For example, FROM (SELECT ...) [AS] foo.  
Character: 24  

请告诉我我的代码是否有任何问题

9 个答案:

答案 0 :(得分:8)

我认为错误信息非常明确:您的子选择需要别名。

SELECT t.salary 
FROM (
      SELECT salary,
          DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSE_RANK 
      FROM geosalary
      ) as t  --- this alias is missing
WHERE t.dense_rank = 2

答案 1 :(得分:2)

SELECT department_id, salary, RANK1 FROM (
    SELECT department_id,
           salary,
           DENSE_RANK ()
              OVER (PARTITION BY department_id ORDER BY SALARY DESC)
              AS rank1
    FROM employees) result  
WHERE rank1 = 3

以上查询将为您提供个别部门的第三高薪。如果您想要与部门无关,那么只需删除PARTITION BY department_id

即可

答案 2 :(得分:0)

您的SQL引擎不知道您正在使用哪个表的“salary”列,这就是您需要使用别名来区分这两列的原因。 试试这个:

SELECT salary
FROM (SELECT G.salary ,DENSE_RANK() OVER(ORDER BY G.SALARY) AS DENSE_RANK FROM geosalary G)
WHERE DENSE_RANK=2;

答案 3 :(得分:0)

WITH salaries AS (SELECT salary, DENSE_RANK() OVER(ORDER BY SALARY) AS DENSE_RANK FROM geosalary)
SELECT * FROM salaries WHERE DENSE_RANK=2;

答案 4 :(得分:0)

错误消息非常明显:您需要为子查询提供别名。

这是一个更简单/更快的选择:

SELECT DISTINCT salary
FROM   geosalary
ORDER  BY salary DESC
OFFSET 1
LIMIT  1;

答案 5 :(得分:0)

select  level, max(salary)
from   geosalary
where   level=2
connect  by
prior   salary>salary
group  by  level;

答案 6 :(得分:0)

如果下面的工资栏中有重复项,查询将给出正确的结果:

WITH tmp_tbl AS
  (SELECT salary,
    DENSE_RANK() OVER (ORDER BY SALARY) AS DENSE_RANK
  FROM geosalary
  )
SELECT salary
FROM tmp_tbl
WHERE dense_rank =
  (SELECT MAX(dense_rank)-1 FROM tmp_tbl
  )
AND rownum=1;

答案 7 :(得分:0)

这是SQL标准

SELECT name, salary
FROM   geosalary 
ORDER BY salary desc
OFFSET 1 ROW
FETCH FIRST 1 ROW ONLY

要计算第n个最高薪水变化抵消值

答案 8 :(得分:-1)

SELECT MAX(salary) FROM geosalary WHERE salary < ( SELECT MAX(salary) FROM geosalary )