获取最近的具有更高“bar”的前一行的“foo”值

Jac*_*las 5 oracle oracle-10g-r2

从这个初始数据:

select level as foo, mod(ora_hash(level),4) as bar from dual connect by level<9;
/*
FOO                    BAR                   
---------------------- ----------------------
1                      3                     
2                      2                     
3                      3                     
4                      3                     
5                      2                     
6                      0                     
7                      3                     
8                      2                      
*/
Run Code Online (Sandbox Code Playgroud)

我想获取foo, bar, prev_foo每一行prev_foo的值,其中是foo最近的“上一个”行(由foo唯一的排序定义)的值,使得bar该行中的值大于bar当前行中的值。换句话说,我想要这个结果:

/*
FOO                    BAR                    PREV_FOO                 
---------------------- ---------------------- ----------------------
1                      3                                           
2                      2                      1                   
3                      3                                          
4                      3                                           
5                      2                      4                     
6                      0                      5                    
7                      3                                           
8                      2                      7                     
*/
Run Code Online (Sandbox Code Playgroud)

我如何实现这一目标?

Jac*_*las 3

这是一种方法,不使用效率很低的分析:

with w as (select level as foo, mod(ora_hash(level),4) as bar from dual connect by level<9)
select foo, bar, (select max(foo) from w where foo<ww.foo and bar>ww.bar) from w ww;
Run Code Online (Sandbox Code Playgroud)