简体   繁体   English

在Oracle中使用ROWNUM获得前5个结果

[英]Getting Top 5 Results using ROWNUM in Oracle

is there something wrong with my query? 我的查询有问题吗? I use below to get the first 5 results ordered by AUDIT_ACTN then AUDIT_STAMP. 我使用下面的方法获得AUDIT_ACTN然后AUDIT_STAMP排序的前5个结果。

SELECT * FROM (SELECT * FROM TABLE_SAMPLE ORDER BY AUDIT_ACTN  
ASC,AUDIT_STAMP ASC)
WHERE ROWNUM <= 5

And I use this to check if I'm getting the correct rows. 我用这个来检查我是否得到了正确的行。

SELECT * FROM TABLE_SAMPLE  ORDER BY 
AUDIT_ACTN,AUDIT_STAMP

The problem is the top 5 rows of the 2nd query is slightly different with the result of the 1st query. 问题是第二个查询的前5行与第一个查询的结果略有不同。 Only 3 rows are the same and with my observation the other 2 are the rownum1 & 2 of the 2nd query. 只有3行是相同的,根据我的观察,其他2行是第二个查询的rownum1和2。 I hope you understood my question I really need help.Thanks! 我希望你理解我的问题我真的需要帮助。谢谢!

I remember reading that ORDER BY would not be guaranteed with subqueries, but here is an alternative solution using ROW_NUMBER -- this includes the ORDER BY in it's OVER clause: 我记得读过ORDER BY不能保证使用子查询,但是这里有一个使用ROW_NUMBER的替代解决方案 - 这包括它的OVER子句中的ORDER BY

SELECT * FROM 
(SELECT Field1, Field2, ROW_NUMBER() OVER (ORDER BY Field2,Field1) AS RN 
 FROM TABLE_SAMPLE 
 ) t 
WHERE RN <= 5

And here is the Fiddle . 这是小提琴

And here is some documentation about Oracle, subqueries, and ORDER BY: 这里有一些关于Oracle,子查询和ORDER BY的文档:

http://docs.oracle.com/javadb/10.8.2.2/ref/rrefsqlj13658.html http://docs.oracle.com/javadb/10.8.2.2/ref/rrefsqlj13658.html

In subqueries, the ORDER BY clause is meaningless unless it is accompanied by one or both of the result offset and fetch first clauses or in conjunction with the ROW_NUMBER function, since there is no guarantee that the order is retained in the outer result set. 在子查询中,ORDER BY子句没有意义,除非它伴随结果offset和fetch first子句中的一个或两个,或者与ROW_NUMBER函数一起使用,因为不能保证顺序保留在外部结果集中。 It is permissible to combine ORDER BY on the outer query with ORDER BY in subqueries. 允许在外部查询中将ORDER BY与子查询中的ORDER BY组合使用。

Good luck. 祝好运。

Try this:This query return top 5 record . 试试这个:这个查询返回前5条记录。

 SELECT * FROM 
    (SELECT Field1, Field2, rank() OVER (ORDER BY Field1,Field2) AS rank
     FROM TABLE_SAMPLE 
     ) t 
    WHERE t.rank <= 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM