问题
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 ?
回答1:
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
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/42251766/oracle-group-using-min-date