oracle中的前10行没有使用'where'条件?

时间:2017-07-11 14:33:47

标签: sql oracle

如何在oracle中选择前10行而不使用'where'条件?

3 个答案:

答案 0 :(得分:4)

试试这个:

  

10g 11g

select
*
from 
   (select empno, sal row_number() 
   over 
   (order by 
            sal desc) rnk from emp)
where rnk <= 10;
  

12C

select 
   ename 
from 
   emp 
order by ename 
fetch first 10 rows only;

答案 1 :(得分:0)

您可以尝试使用Windows分析功能,在本例中为

ROW_NUMBER()OVER(分段为col1,col2 ORDER BY col3)

你必须在PARTITION BY之后指明“划分”记录的列(如GROUP BY)(也没有列),你必须指定一个或多个列用于“排序”(在ORDER BY之后) 例如:

SELECT * 
FROM (SELECT YOURTABLE.*,
            ROW_NUMBER() OVER (PARTITION BY xx  ORDER BY yy) AS RN
      FROM YOURTABLE) A
WHERE RN<= yourvalue

EG。在以下样本数据中提取每个人的两个最高收入:

CREATE TABLE TT1 ( LASTNAME VARCHAR2(50), INCOME NUMBER(12,2));
INSERT INTO TT1 VALUES ('Stuart', 1000);
INSERT INTO TT1 VALUES ('Stuart', 2000);
INSERT INTO TT1 VALUES ('Radcliff', 3500);
INSERT INTO TT1 VALUES ('Radcliff', 4500);
INSERT INTO TT1 VALUES ('Radcliff', 6000);
INSERT INTO TT1 VALUES ('Stuart', 4000);

SELECT * 
FROM (SELECT TT1.*,
      ROW_NUMBER() OVER (PARTITION BY LASTNAME ORDER BY INCOME DESC) AS RN
      FROM TT1) A
WHERE RN<=2;

输出:

Radcliff    6000    1
Radcliff    4500    2
Stuart      4000    1
Stuart      2000    2

答案 2 :(得分:0)

  

不使用&#39;在哪里&#39;条件

在oracle 12c上:

SELECT * FROM table
ORDER BY somecolumn
FETCH FIRST 10 ROWS ONLY

在早期版本中,如果您真的不想使用WHERE条款,请使用JOIN .. ON condition来表达条件first to 10 rows

SELECT t.*
FROM (
  SELECT t.*, rownum As rn
  FROM table t
  ORDER BY somecolumn
) t
JOIN dual ON t.rn <= 10