如何在订购后限制oracle查询返回的行数?

时间:2016-09-26 12:56:10

标签: sql oracle oracle11g

我知道这是一个重复的问题,但其他帖子并没有解决我的问题。

我试图只显示以下查询产生的前2行。

SELECT
    AVG(sessionprice),
    branchsuburb
FROM    branch,
        sessions
WHERE branch.branchid = sessions.branchid
GROUP BY branchsuburb
ORDER BY AVG(sessionprice) DESC;

该查询将返回所有结果,但我希望将其限制为仅排在前2位(就哪一行的平均值最高而言)。我在这篇文章中试过了fetch函数 How do I limit the number of rows returned by an Oracle query after ordering? 但它只是返回一个ORA-00933错误。我知道我一定是犯了一些愚蠢的错误,但我无法弄清楚。有没有办法在不使用子查询的情况下执行此操作?

添加fetch函数后的代码如下所示

SELECT
    AVG(SESSIONPRICE),
    BRANCHSUBURB
FROM    BRANCH,
        SESSIONS
WHERE BRANCH.BRANCHID = SESSIONS.BRANCHID
GROUP BY BRANCHSUBURB
ORDER BY AVG(SESSIONPRICE) DESC
FETCH FIRST 2 ROWS ONLY;

4 个答案:

答案 0 :(得分:5)

最近在Oracle中引入了

FETCH。在旧版本中,您需要使用子查询:

SELECT bs.*
FROM (SELECT avg(sessionprice), branchsuburb
      FROM branch b JOIN
           sessions s
           ON b.branchid = s.branchid
      GROUP BY branchsuburb
      ORDER BY avg(sessionprice) DESC
     ) bs
WHERE rownum <= 2;

答案 1 :(得分:1)

您可以使用CTE并实现此目的;

with tbl as (SELECT avg(sessionprice), branchsuburb
              FROM branch b JOIN
                   sessions s
                   ON b.branchid = s.branchid
              GROUP BY branchsuburb
              ORDER BY avg(sessionprice) DESC )
select tbl.* from tbl
WHERE rownum <= 2;

答案 2 :(得分:0)

Yon可以试试这个。这也是分页的开始和结束位置

SELECT * FROM (SELECT inner_query.*, rownum rnum FROM (SELECT * FROM table_name ORDER BY column_name) inner_query WHERE rownum <= 20) WHERE rnum >= 1;

rownum 中没有记录, rnum 表示起始位置。

答案 3 :(得分:0)

select * from (SELECT
    AVG(SESSIONPRICE),
    BRANCHSUBURB
FROM    BRANCH,
        SESSIONS
WHERE BRANCH.BRANCHID = SESSIONS.BRANCHID
GROUP BY BRANCHSUBURB
ORDER BY AVG(SESSIONPRICE) DESC ) where ROWID <= 2