HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

What is the simplest way of excluding the current row from the result of an analytic?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
fromresultanalyticthewhatsimplestexcludingwaycurrentrow

Problem

I want to do something like the following:

with w as ( select level as foo,
decode(level,8,1,mod(level,4))*100 as bar
from dual connect by level

but I want
lowest to show the next lowest if the current row is the lowest for a given bar, or null if it is the only one. In other words I want this result:

/*
FOO BAR PSEUDOLOWEST
---------------------- ---------------------- ----------------------
4 0
1 100 5
5 100 1
8 100 1
2 200 6
6 200 2
3 300 7
7 300 3
*/
`

What is the simplest way of achieving this?

Solution

There may be a simpler way, but here is a solution. If the current row is the minimum foo for the bar, then we always want the next (lead) foo. When there is only one foo for a bar the lead will always be null and for every other case we really do want the minimum foo for the bar.

with w as (select level as foo, decode(level,8,1,mod(level,4))*100 as bar
   from dual connect by level<9) 
select foo, bar
   , case 
        when foo = min(foo) over (partition by bar) 
           then lead(foo) over (partition by bar ORDER BY foo)
        else min(foo) over (partition by bar) 
     end pseudolowest
from w;


Unfortunately rows excluding current row doesn't exist.

Code Snippets

with w as (select level as foo, decode(level,8,1,mod(level,4))*100 as bar
   from dual connect by level<9) 
select foo, bar
   , case 
        when foo = min(foo) over (partition by bar) 
           then lead(foo) over (partition by bar ORDER BY foo)
        else min(foo) over (partition by bar) 
     end pseudolowest
from w;

Context

StackExchange Database Administrators Q#13803, answer score: 3

Revisions (0)

No revisions yet.