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!

over partition: how to use to return the max of two columns

689340Mar 5 2009 — edited Mar 5 2009
For each unique id, I want to select the value of col2 in the record with the most recent date.
When the rows with the same IDs have the same dates, I want the max value from col2.
I want one row for each ID, but I'm getting two rows for ID 3333333.

with data as
(
select 1111111 as id, 'a' as col2, to_date('01-JAN-09','dd-mon-yyyy') as the_date from dual union all
select 2222222 as id, 'b' as col2, to_date('02-JAN-09','dd-mon-yyyy') as the_date from dual union all
select 2222222 as id, 'c' as col2, to_date('03-JAN-09','dd-mon-yyyy') as the_date from dual union all
select 2222222 as id, 'd' as col2, to_date('04-JAN-09','dd-mon-yyyy') as the_date from dual union all
select 3333333 as id, 'e' as col2, to_date('05-JAN-09','dd-mon-yyyy') as the_date from dual union all
select 3333333 as id, 'f' as col2, to_date('05-JAN-09','dd-mon-yyyy') as the_date from dual
)
select id, col2, the_date
from
(
select id, the_date, col2, max(the_date) over (partition by id) as max_the_date, max(col2) over (partition by col2) as max_col2
from data
)
where the_date = max_the_date and col2 = max_col2 order by id


Expecting this:
ID COL2 THE_DATE
1111111 a 1/1/0009
2222222 d 1/4/0009
3333333 f 1/5/0009

but I'm getting 2 rows for ID 3333333

Any suggestions?
This post has been answered by 667579 on Mar 5 2009
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 2 2009
Added on Mar 5 2009
2 comments
469 views