Oracle SQL:按条件后的日期返回以前的n行订单

Oracle SQL:按条件后的日期返回以前的n行订单,sql,oracle,sql-order-by,Sql,Oracle,Sql Order By,我需要在一组按日期排序的数据条件之后返回前3行。请参见以下带有一些数据的查询: 选择发票、客户识别号、销售日期、已处理 来自销售 其中cli_id='490727' 按销售日期订购 发票客户识别号销售日期已处理 7995781 490727 04/07/2018 15:30:36西 7995782 490727 04/07/2018 15:30:39 Q 7995783 490727 04/07/2018 15:30:41 Q 7995784 490727 04/07/2018 15:30:43

我需要在一组按日期排序的数据条件之后返回前3行。请参见以下带有一些数据的查询:

选择发票、客户识别号、销售日期、已处理 来自销售 其中cli_id='490727' 按销售日期订购

发票客户识别号销售日期已处理 7995781 490727 04/07/2018 15:30:36西 7995782 490727 04/07/2018 15:30:39 Q 7995783 490727 04/07/2018 15:30:41 Q 7995784 490727 04/07/2018 15:30:43 Q 7995792 490727 04/07/2018 15:31:01 W==> 7995793 490727 04/07/2018 15:31:03 Q 799579490727 04/07/2018 15:31:06 Q 7995795 490727 04/07/2018 15:31:08 Q 我需要返回前3行before的某些条件==>processed='W' 例如:想知道前面3行的PROCESSED='W',其中发票是7995792。它将返回:
7995793、7995794和7995795在Oracle 12C中,您可以使用:

select s.*
from sales s
where s.sale_date < (select s2.sale_date
                     from sales s2
                     where s2.cli_id = s.cli_id and s2.processed = 'W'
                    ) and
      s.cli_id = 490727
order by s.sale_date desc
fetch first 3 rows only;
在早期版本中,您需要一个子查询:

select s.*
from (select s.*
      from sales s
      where s.sale_date < (select s2.sale_date
                           from sales s2
                           where s2.cli_id = s.cli_id and s2.processed = 'W'
                          ) and
            s.cli_id = 490727
      order by s.sale_date desc
     ) s
where rownum <= 3;