postgresql 如何找出第二高工资的员工?

lo8azlld  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(9)|浏览(127)

已创建名为geosalary的表,列为nameidsalary

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

我的代码有什么问题?

mccptt67

mccptt671#

我认为错误信息非常清楚:你的子选择需要别名。

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
omqzjyyz

omqzjyyz2#

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

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

这将根据请求查找“第二高工资”(1行)。其他查询查找具有第二高工资的所有员工(1-n行)。
我添加了NULLS LAST,因为null值通常不应该排在第一位。参见:

  • 按ASC列排序,但先按NULL值排序?
vuv7lop3

vuv7lop33#

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

gwo2fgha

gwo2fgha4#

您的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;
ee7vknir

ee7vknir5#

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

bnlyeluc6#

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

nszi6y057#

如果下面的工资列重复,查询将给出正确的结果:

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;
jyztefdp

jyztefdp8#

这里是SQL标准

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

计算第n个最高薪资变动冲抵值

vmjh9lq9

vmjh9lq99#

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

相关问题