Select TOP N and BOTTOM N

后端 未结 2 1918
醉话见心
醉话见心 2021-01-27 19:03

Trying to fetch top n bottom n rows. Though it gives me result but, it takes lot of time. I believe it scans table twice.

Code used:
WITH TI AS
(SELECT * FROM
(S         


        
2条回答
  •  悲哀的现实
    2021-01-27 19:27

    The best way to solve this problem depends in part on your Oracle version. Here is a very simple (and, I suspect, very efficient) solution using the match_recognize clause, added in version 12.1.

    I illustrate it using the EMPLOYEES table in the standard HR schema, ordering by SALARY. The only trick here is to select the top and bottom five rows, and to ignore everything in between; that (the "ignoring") is what the {- ... -} operator does in the pattern sub-clause.

    select employee_id, first_name, last_name, salary
    from   hr.employees
    match_recognize(
      order by salary desc
      all rows per match
      pattern ( a{5} {- a* -} a{5} )
      define a as 0 = 0             -- For reasons known only to Oracle, DEFINE is required.
    );
    
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                     SALARY
    ----------- -------------------- ------------------------- ----------
            100 Steven               King                           24000
            101 Neena                Kochhar                        17000
            102 Lex                  De Haan                        17000
            145 John                 Russell                        14000
            146 Karen                Partners                       13500
            135 Ki                   Gee                             2400
            127 James                Landry                          2400
            136 Hazel                Philtanker                      2200
            128 Steven               Markle                          2200
            132 TJ                   Olson                           2100
    

提交回复
热议问题