在Oracle中选择前两行

时间:2016-10-05 10:35:13

标签: sql oracle greatest-n-per-group

我试图只显示Oracle中的前两行,但是我无法找到任何可行的内容。

我目前有

SELECT BRANCH.BRANCHID, BRANCHNAME, AVG(SESSIONPRICE)
FROM BRANCH, SESSIONS
WHERE SESSIONS.BRANCHID = BRANCH.BRANCHID
GROUP BY BRANCHNAME, BRANCH.BRANCHID
ORDER BY AVG(SESSIONPRICE) DESC

返回此

B2      A     18.67
B4      B     17.57
B3      C     15.44
B1      D     13.99

但是,我只想要这个表的前两行。

我到底该怎么做?

3 个答案:

答案 0 :(得分:0)

从Oracle 9i开始,RANK()和DENSE_RANK()函数可用于确定TOP N行。例子:

  

使用RANK()

获得前2名分支
SELECT ename, sal 
  FROM ( SELECT BRANCH.BRANCHID, BRANCHNAME, AVG(SESSIONPRICE) RANK() OVER (ORDER BY AVG(SESSIONPRICE) DESC) avg_rank
           FROM BRANCH) 
 WHERE avg_rank<= 2;
  

使用DENSE_RANK()

获取前2个分支
SELECT ename, sal 
  FROM ( SELECT BRANCH.BRANCHID, BRANCHNAME, AVG(SESSIONPRICE) DENSE_RANK() OVER (ORDER BY AVG(SESSIONPRICE) DESC) avg_Dense_rank
           FROM BRANCH) 
 WHERE avg_Dense_rank<= 2;

答案 1 :(得分:-1)

我再次编辑了答案:

SELECT *
FROM (SELECT BRANCH.BRANCHID, BRANCHNAME, AVG(SESSIONPRICE)
FROM BRANCH, SESSIONS
WHERE SESSIONS.BRANCHID = BRANCH.BRANCHID

GROUP BY BRANCHNAME, BRANCH.BRANCHID
ORDER BY AVG(SESSIONPRICE) DESC
)
WHERE ROWNUM <= 2;

答案 2 :(得分:-2)

使用RowNUM:

用于指定要返回的记录数。

            SELECT BRANCH.BRANCHID, BRANCHNAME, AVG(SESSIONPRICE)
            FROM BRANCH, SESSIONS
            WHERE 
            ROWNUM <= 2 and SESSIONS.BRANCHID = BRANCH.BRANCHID
            GROUP BY BRANCHNAME, BRANCH.BRANCHID
            ORDER BY AVG(SESSIONPRICE) DESC ;