Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

11g equivalent of Excel LARGE() function? (nth largest in set)

user12048529Aug 22 2012 — edited Aug 24 2012
I've been spinning my wheels on this and figured I'd give the forums a try.

I need to find the 13th largest value over the previous 52 weeks. I can set the window size correctly using ROWS 52 PRECEDING AND CURRENT ROW ORDER BY WEEK, but then I need another sort for the nTH largest within that partition. NTH_VALUE is close but what I really need is NTH_LARGEST_VALUE. Excel has a LARGE() function to do this.

Any thoughts for achieving this? See the example below:

Column desired_output is what I'm looking to achieve. It is the 2nd largest value over the current row and the previous 2 rows (ordered by week). Assume no relationship between week and val. These values just used for illustration purposes.
with tab as 
(
    select to_date('4-jan-2012', 'dd-mon-yyyy')+(level-1)*7 week, 
           to_number(to_char(to_date('4-jan-2012', 'dd-mon-yyyy')+(level-1)*7,'dd')) val,
           case when level in (1,2) then null
                when level = 3 then 11
                when level = 4 then 18
                when level = 5 then 18
                when level = 6 then 8
                when level = 7 then 8
                when level = 8 then 15
                when level = 9 then 22
                when level = 10 then 22
           end desired_result
      from dual connect by level <= 10
) 
select week, val, desired_result
  from tab 
order by week;  
WEEK             VAL DESIRED_RESULT
--------- ---------- --------------
04-JAN-12          4
11-JAN-12         11
18-JAN-12         18             11
25-JAN-12         25             18
01-FEB-12          1             18
08-FEB-12          8              8
15-FEB-12         15              8
22-FEB-12         22             15
29-FEB-12         29             22
07-MAR-12          7             22

10 rows selected.
Any advice would be appreciated. Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 21 2012
Added on Aug 22 2012
13 comments
483 views