sql - 使用 rownum 选择表格的第二行

标签 sql oracle oracle10g rownum

我尝试了以下查询:

select empno from (
                   select empno 
                     from emp
                    order by sal desc
                  )
where rownum = 2

这不会返回任何记录。

当我尝试这个查询时
 select rownum,empno from (
                        select empno from emp order by sal desc) 

它给了我这个输出:
ROWNUM  EMPNO      
1       7802        
2       7809    
3       7813    
4       7823

谁能告诉我我的第一个查询有什么问题?为什么添加 ROWNUM 过滤器时不返回任何记录?

最佳答案

To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires that ROWNUM is greater than 2, no rows are selected and ROWNUM is never incremented beyond 1.

The bottom line is that conditions such as the following will work as expected.

.. WHERE rownum = 1;

.. WHERE rownum <= 10;

While queries with these conditions will always return zero rows.

.. WHERE rownum = 2;

.. WHERE rownum > 10;



引自 Understanding Oracle rownum

您应该以这种方式修改您的查询以便工作:
select empno
from
    (
    select empno, rownum as rn 
    from (
          select empno
          from emp
          order by sal desc
          )
    )
where rn=2;

编辑 :我已经更正了查询以获得 rownum Sal desc 的订单

关于sql - 使用 rownum 选择表格的第二行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9240192/

相关文章:

SQL Server 2012 Windowing函数计算运行总计

java - 如何去掉java sql语句中的许多占位符(问号)

sql - Oracle 11 SQL : Split 1 row into x rows and insert a new column

oracle - 如何找出存储过程中使用了哪些表/ View /同义词

sql - SQL 中的分析函数 FIRST_VALUE 如何工作

mysql - mySql 与 Ms-Sql 和 Oracle 在连接具有排序结果集的表时的不同行为

sql - 如果我更改表以添加分区,我会丢失 Oracle SQL 中的数据吗?

sql - Oracle 一小时后执行触发器

sql - 如何使用oracle数据库日期表获取最小日期

oracle - 可以将 oracle 11g 客户端与 10g 服务器一起使用吗?