Skip to content
Advertisement

Max analytical function plus windowed ordering is not working as expected

I have a table with status and location, the following is the data. I’d like to get max status partitioned by location using custom ordering. Any idea what needs to change? Right now it is giving only max value, irrespective of the ordering i mentioned.

The custom ordering is 1 > 3 > 2

status | location
  1    | 11 
  2    | 11 
  2    | 12 
  3    | 12
  3    | 11

Expected result for location 11 : 1 Expected result for location 12 : 3

Query:

select max(status) over (partition by location order by decode(status, '1',6,'3',5,'2',4,3) 
                         rows between unbounded preceding and unbounded following) mx from items;

http://sqlfiddle.com/#!4/ed9e7e/13

create table items
( status varchar2(1), location number(9)
);

insert into items values('1',123);

insert into items values('2',123);

insert into items values('3',123);

insert into items values('4',123);

Advertisement

Answer

I think you want first_value():

select first_value(status) over (partition by location
                                 order by decode(status, '1', 6, '3', 5, '2', 4, 3) 
                                ) mx
from items;

I’m not a big fan of decode(), but it is a concise way to express what you want. I prefer case expressions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement