Oracle group part of row and get row with latest timestamp

独自空忆成欢 提交于 2019-12-11 09:36:18

问题


I have a select that gives me this result:

 - ID   | System    | Type1 | NID       | Name_ | Type2__   | Date 
 - 24   | AA-Tool   | PRIV  | 816       | Name1 | IMPLICIT  | 17.12.2014
 - 24   | AA-Tool   | PRIV  | 816       | Name1 | EXPLICIT  | 19.12.2014
 - 24   | AA-Tool   | PRIV  | 816       | Name1 | EXPLICIT  | 20.12.2014
 - 25   | BB-Tool   | PRIV  | 817       | Name2 | EXPLICIT  | 20.12.2014
 - 25   | BB-Tool   | PRIV  | 817       | Name2 | EXPLICIT  | 21.12.2014

So ID, System, Type1, NID and Name should be distinct and Type2 and Date should be the last entry by date.. This should be the result:

 - 24   | AA-Tool   | PRIV  | 816       | Name1 | EXPLICIT  | 20.12.2014
 - 25   | BB-Tool   | PRIV  | 817       | Name2 | EXPLICIT  | 21.12.2014

I hope thats understandable :)

Thanks, Michael


回答1:


Try this:

SELECT a.ID, a.System, a.Type1, a.NID, a.Name_, a.Type2__, a.Date
FROM tableA a 
INNER JOIN (SELECT a.ID, a.System, a.Type1, a.NID, a.Name_, MAX(a.Date) Date 
            FROM tableA a
            GROUP BY a.ID, a.System, a.Type1, a.NID, a.Name_
           ) b ON a.ID = b.ID AND a.System = b.System AND 
                  a.Type1 = b.Type1 AND a.NID = b.NID AND 
                  a.Name_ = b.Name_ AND a.Date = b.Date;



回答2:


Another approach could be:

SELECT t.*
  FROM(SELECT t.*,
              ROW_NUMBER() OVER (PARTITION BY id, system, type1, nid, name 
                                     ORDER BY date DESC) AS rn
         FROM tabelA t
      )
 WHERE rn = 1

Maybe it will help you.




回答3:


SELECT   DISTINCT *
FROM    (   SELECT   id,
                     system,
                     type_id,
                     nid,
                     name_,
                     type2__,
                     date,
                     RANK() OVER (PARTITION BY id, system, type1, nid ORDER BY date DESC) AS reverse_date_rank
            FROM     sometable )
WHERE    reverse_date_rank = 1;

The DISTINCT in the outer subquery is only required if you can get multiple identical name_/type2__ entries for a certain date, as they will return an equal reverse_date_rank.



来源:https://stackoverflow.com/questions/27563797/oracle-group-part-of-row-and-get-row-with-latest-timestamp

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