Reputation: 2577
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
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
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
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