Oracle group using min date

 ̄綄美尐妖づ 提交于 2019-12-23 04:28:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!