Patrick
Patrick

Reputation: 2577

Oracle group using min date

I have a statement like this:

 select REFNUMBER,
        SomeDate,
        Somecolumn1,
        Somecolumn2
 from Table

How can I select the row associated with the lowest date grouped by REFNUMBER ?

Upvotes: 0

Views: 4850

Answers (3)

user5683823
user5683823

Reputation:

Use the first/last aggregate function and avoid a subquery:

select   refnumber,
         min(somedate)                                              as somedate,
         min(somecolumn1) keep (dense_rank first order by somedate) as somecolumn1,
         min(somecolumn2) keep (dense_rank first order by somedate,
                                                       somecolumn1) as somecolumn2
from     table_name
group by refnumber

Upvotes: 2

Oto Shavadze
Oto Shavadze

Reputation: 42863

If there are several identical lowest dates by one REFNUMBER, this will give all minimal date rows for this REFNUMBER. (not only one)

    SELECT Table.* FROM Table
    INNER JOIN (SELECT REFNUMBER, MIN(SomeDate) AS mindt FROM Table GROUP BY REFNUMBER) t
    ON
    Table.REFNUMBER = t.REFNUMBER AND Table.SomeDate = t.mindt 

Upvotes: 0

MT0
MT0

Reputation: 168740

Use the ROW_NUMBER() analytic function:

SELECT *
FROM   (
  SELECT REFNUMBER,
         SomeDate,
         Somecolumn1,
         Somecolumn2,
         ROW_NUMBER() OVER ( PARTITION BY REFNUMBER ORDER BY SomeDate ) As rn
  FROM   Table
)
WHERE  rn = 1

Upvotes: 4

Related Questions