1

创建了以geosalarynameid和命名的表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  

我的代码有什么问题?

4

9 回答 9

10

我认为错误信息很清楚:您的子选择需要一个别名。

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
于 2013-07-12T07:32:13.620 回答
5

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

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

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

这将找到“第二高薪水”(1 行),而不是查找所有薪水第二高的员工(1-n 行)的其他查询。

我补充说NULLS LAST,因为 NULL 值通常不应该为此目的排名第一。看:

于 2013-07-12T07:34:52.007 回答
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

于 2014-11-11T19:04:59.147 回答
0
select  level, max(salary)
from   geosalary
where   level=2
connect  by
prior   salary>salary
group  by  level;
于 2013-07-14T17:11:20.173 回答
0
WITH salaries AS (SELECT salary, DENSE_RANK() OVER(ORDER BY SALARY) AS DENSE_RANK FROM geosalary)
SELECT * FROM salaries WHERE DENSE_RANK=2;
于 2013-07-12T07:09:38.697 回答
0

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

SELECT salary
FROM (SELECT G.salary ,DENSE_RANK() OVER(ORDER BY G.SALARY) AS DENSE_RANK FROM geosalary G)
WHERE DENSE_RANK=2;
于 2013-07-12T07:06:26.993 回答
0

这是SQL标准

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

计算第 n 个最高工资变动补偿值

于 2019-05-06T06:19:24.563 回答
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;
于 2017-05-21T16:40:37.310 回答
-1
SELECT MAX(salary) FROM geosalary WHERE salary < ( SELECT MAX(salary) FROM geosalary )
于 2013-07-12T07:06:56.353 回答