Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.server -> Re: Fastest way of getting value associated with max(...)

Re: Fastest way of getting value associated with max(...)

From: Kim Berg Hansen <kibeha_at__no_spam_please_post6.tele.dk>
Date: Wed, 25 Feb 2004 13:23:45 +0100
Message-ID: <403c93d2$0$1618$edfadb0f@dread14.news.tele.dk>


"FC" <flavio_at_tin.it> wrote in message
news:2bd78ddf.0402250153.6ccdaf6_at_posting.google.com...
> SELECT max(to_char(exch_date,'YYYYMMDD') || '-' || to_char(exch_rate))
> INTO mystr
> FROM exchange
> WHERE curr_from = :new.curr_from_code
> AND curr_to = :new.curr_to_code
> AND exch_date <= sysdate;
>

> The best alternative way I found so far is:
>
> select exch_rate
> from exchange
> where curr_from = :new.curr_from_code
> and curr_to = :new.curr_to_code
> and exch_date = (select max(exch_date)
> from exchange
> where curr_from = :new.curr_from_code
> and curr_to = :new.curr_to_code
> and exch_date <= sysdate);

If its Oracle 9i then this could be a possibility :

select max(exch_rate) keep (dense_rank last order by exch_date) from exchange
where curr_from = :new.curr_from_code
and curr_to = :new.curr_to_code
and exch_date <= sysdate;

That means that for those records having the last exch_date, select the max of exch_rate.
As presumably there is only one record for each exch_date, that should be OK.
In case you have ties with same exch_date, the original logic would fail too.

For Oracle 8i analytics could be used like this :

select last_exch_rate from (
  select last_value(exch_rate) over (order by exch_date rows between unbounded preceding and unbounded following) last_exch_rate   from exchange
  where curr_from = :new.curr_from_code
  and curr_to = :new.curr_to_code
  and exch_date <= sysdate
) where rownum = 1;

Hope those may be better ? But not sure... Try them out and see :-)

/KiBeHa Received on Wed Feb 25 2004 - 06:23:45 CST

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US