获取Oracle上的特定行数据

时间:2016-03-18 09:28:59

标签: sql oracle

我想获取特定的行数据。 但是在这个查询中它显示了错误。在这里我想得到第5行

  

ORA-00904:" RN":无效标识符

代码

   SELECT NEWSDATE,ROWNUM AS RN
   FROM NEWS
   WHERE NEWSNO='100000' AND (CAT='LR' OR CRT ='LD') AND RN = 5 //<-- It highlighted this RN is invalid
   ORDER BY  NEWSDATE ASC

4 个答案:

答案 0 :(得分:3)

试试这个:

select * from (
  SELECT NEWSDATE,row_number() over (order by newsdate) AS RN
  FROM   NEWS
  WHERE  NEWSNO='100000' AND (CAT='LR' OR CRT ='LD')
)
where rn = 5;

答案 1 :(得分:2)

您不能使用SELECT子句中WHERE子句中定义的列别名,因为首先会计算WHERE子句。为了使您的查询在语法上有效,它将是:

SELECT   NEWSDATE,ROWNUM AS RN
FROM     NEWS
WHERE    NEWSNO='100000' AND (CAT='LR' OR CRT ='LD') AND ROWNUM = 5
ORDER BY NEWSDATE ASC

但是,这将永远不会返回任何行,因为会考虑生成的第一行并将其作为ROWNUM=1丢弃,然后它将考虑生成的第二行,并且由于第一行被丢弃,因此也会ROWNUM=1 1}}并被丢弃。这将重复令人作呕,直到所有行都被丢弃,并且没有一行会被认为具有比{1}更高的ROWNUM

要使其工作,您需要考虑在ROWNUM子句生效之前应用ORDER BY;所以,如果你想对有序行进行编号,那么首先应用ORDER BY,然后在外部查询中分配ROWNUM,然后最后,在进一步的外部查询中,过滤该数字:

SELECT NEWDATE
FROM   (
  SELECT NEWDATE,
         ROWNUM AS RN -- Assign the ROWNUM in the outer query after the ORDER BY
  FROM   (
    SELECT   NEWSDATE
    FROM     NEWS
    WHERE    NEWSNO='100000' AND (CAT='LR' OR CRT ='LD')
    ORDER BY NEWSDATE ASC
  )
  WHERE RN <= 5 -- This WHERE clause is not necessary but might make it more efficient as
                -- it can immediately stop filtering and discard all rows after the 5th.
)
WHERE  RN = 5; -- Then in a further outer query filter on RN

答案 2 :(得分:1)

您对ROWNUM的理解不正确。请阅读此article以了解其工作原理。

SELECT *
  FROM (SELECT NEWSDATE, ROW_NUMBER() OVER (ORDER BY NEWSDATE) AS RN
          FROM NEWS
         WHERE NEWSNO = '100000'
           AND (CAT = 'LR' OR CRT = 'LD')
         ORDER BY NEWSDATE ASC)
 WHERE RN = 5;

答案 3 :(得分:0)

试试这个

 select * from ( 
       select a.*, rownum rnum  from ( 
            SELECT NEWSDATE  FROM NEWS  
            WHERE NEWSNO='100000' AND (CAT='LR' OR CRT ='LD')  
            ORDER BY  NEWSDATE ASC ) 
          where rownum <= 5 )
    where rnum >= 5