获得满足条件的前几行

时间:2018-04-10 06:13:27

标签: sql oracle oracle11g

我需要得到C ='1'的前两行, 我正在通过TimeStamp Descending命令查询,我不想要 要查询的最后一行

    A      B  C   TimeStamp
 ------------------------------------
  foo    one  1   20180405153936
  foo    two  1   20180405153936
  foo    two  2   20180405115417
  foo    one  2   20180405115053
  foo  three  1   20180405113923

2 个答案:

答案 0 :(得分:1)

您可以使用ROWNUM构造,但请记住,除非您打包排序选择,否则ROWNUM将按行添加到表中的顺序返回行。

SELECT * FROM
    (SELECT * FROM 
         yourTable
     WHERE C = 1 
     ORDER BY "TimeStamp" DESC)
WHERE ROWNUM <= 2 

编辑

鉴于添加的信息,以下内容可能比使用ROWNUM更好。

SELECT * FROM 
    yourTable
WHERE 
    C = 1 AND 
    "TimeStamp" > (
        SELECT MIN("TimeStamp") FROM yourTable WHERE C = 1
    ) 
ORDER BY "TimeStamp" DESC

答案 1 :(得分:0)

您可以使用ROWNUM

SELECT * FROM
(SELECT * FROM 
     Table1 
 WHERE C=1
 ORDER BY "TimeStamp" DESC)
WHERE ROWNUM <= (SELECT COUNT(*) FROM Table1 WHERE C=1)-1

<强>演示

  

http://sqlfiddle.com/#!4/08ed98/11