gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:05:03 25 4
gpt4 key购买 nike

我尝试了以下查询:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com