I’m quite new to Oracle and I recently ran into a problem :
I have a table with the following columns : person_id, account_login, add_date.
person_id | account_login | add_date
----------|---------------|------------
1 | user1 | 2012-07-10
1 | user2 | 2012-07-09
2 | user3 | 2012-07-05
2 | user4 | 2012-07-04
A person can have multiple account_logins. For every person, I want to fetch the oldest account_login :
person_id | account_login | add_date
----------|---------------|------------
1 | user2 | 2012-07-09
2 | user4 | 2012-07-04
So what I did was :
select
person_id,
MAX(account_login) KEEP (DENSE_RANK FIRST ORDER BY add_date)
from
table
group by
person_id;
I get exactly the result I want, but I think the syntax of my query is far from good.. Oracle forces me to use an aggregate function and I used MAX() or MIN() knowing that it’s completely senseless..
Is there a way to write the query better than this? (Oracle 11g)
You can use DENSE_RANK as an analytic alone, and select from the resulting query:
Not sure which version you consider more elegant. It also does not address what to do if you have two accounts created on the same date for a particular person_id. If you’ve also got a time component in your add_date then you should be okay. If ties are likely, perhaps ROW_NUMBER() would give you a more desirable outcome.