【发布时间】:2018-11-13 23:21:28
【问题描述】:
所以我想输出一个大表,但是我只想查看 20 到 30 之间的行。
我试过了
select col1, col2
from table
where rownum<= 30 and rownum>= 20;
但是sql报错了
我也试过 --where rownum 在 20 到 30 之间 它也没有工作。
那么最好的方法是什么?
【问题讨论】:
标签: sql oracle filter subset rows
所以我想输出一个大表,但是我只想查看 20 到 30 之间的行。
我试过了
select col1, col2
from table
where rownum<= 30 and rownum>= 20;
但是sql报错了
我也试过 --where rownum 在 20 到 30 之间 它也没有工作。
那么最好的方法是什么?
【问题讨论】:
标签: sql oracle filter subset rows
SELECT *
FROM T
ORDER BY I
OFFSET 20 ROWS --skips 20 rows
FETCH NEXT 10 ROWS ONLY --takes 10 rows
这仅显示第 21 到 30 行。请注意此处需要对数据进行排序,否则每次可能得到不同的结果。
另请参阅文档中的here。
附录:如显示的可能重复链接中所示,您的问题是如果没有编号为 19 的行,则不能有编号为 20 的行。这就是为什么 rownum-approach 只能采用前 x 条记录,但是当您需要跳过记录时,您需要通过选择子查询中的 rownum 或使用 offset ... fetch
使用 rownum 的方法示例(对于较低的 oracle 版本或其他):
with testtab as (
select 'a' as "COL1" from dual
union all select 'b' from dual
union all select 'c' from dual
union all select 'd' from dual
union all select 'e' from dual
)
select * from
(select rownum as "ROWNR", testtab.* from testtab) tabWithRownum
where tabWithRownum.ROWNR > 2 and tabWithRownum.ROWNR < 4;
--returns only rownr 3, col1 'c'
【讨论】:
每当您使用 rownum 时,它都会计算您的查询返回的行数。因此,如果您尝试通过选择 rownum 20 和 30 之间的所有记录进行过滤,那只有 10 行,所以 20 和 30 不存在。但是,您可以使用 WITH(无论您想命名它),然后包装您的查询并重命名您的 rownum 列。这样您就可以从您的选择中进行选择。例子。
with T as (
select requestor, request_id, program, rownum as "ROW_NUM"
from fnd_conc_req_summary_v where recalc_parameters='N')
select * from T where row_num between 20 and 30;
【讨论】: