Oracle SQL order by in subquery problems!

后端 未结 4 1316
终归单人心
终归单人心 2020-12-31 04:49

I am trying to run a subquery in Oracle SQL and it will not let me order the subquery columns. Ordering the subquery is important as Oracle seems to choose at will which of

4条回答
  •  庸人自扰
    2020-12-31 05:32

    Both dcw and Dems have provided appropriate alternative queries. I just wanted to toss in an explanation of why your query isn't behaving the way you expected it to.

    If you have a query that includes a ROWNUM and an ORDER BY, Oracle applies the ROWNUM first and then the ORDER BY. So the query

    SELECT *
      FROM emp
     WHERE rownum <= 5
     ORDER BY empno
    

    gets an arbitrary 5 rows from the EMP table and sorts them-- almost certainly not what was intended. If you want to get the "first N" rows using ROWNUM, you would need to nest the query. This query

    SELECT *
      FROM (SELECT *
              FROM emp
             ORDER BY empno)
     WHERE rownum <= 5
    

    sorts the rows in the EMP table and returns the first 5.

提交回复
热议问题