Group By with MAX(TIMESTAMP) [duplicate]

给你一囗甜甜゛ 提交于 2019-12-12 01:54:57

问题


I have a table showing letter id with year and created timestamp.I have to list the latest timestamp for every year.

For example: This is my DATA.

  Letter ID YEAR               TIMESTAMP
  1411      2013     17-NOV-14 09.18.01.000000000 AM
  1412      2013     16-NOV-14 09.18.01.000000000 AM
  1413      2013     15-NOV-14 09.18.01.000000000 AM
  1414      2013     14-NOV-14 09.18.01.000000000 AM    
  1415      2013     13-NOV-14 09.18.01.000000000 AM
  1416      2012     17-NOV-14 10.18.01.000000000 AM
  1417      2012     16-NOV-14 10.18.01.000000000 AM

The desired result should be:

Letter ID   YEAR     TIMESTAMP
  1411      2013     17-NOV-14 09.18.01.000000000 AM
  1416      2012     17-NOV-14 10.18.01.000000000 AM

Please get me to solve this...


回答1:


select * from (
select Letter_ID,YEAR,TIMESTAMP,
       row_number()over(partition by YEAR order by TIMESTAMP desc) RN from DATA
) WHERE RN = 1

Hope helps you.




回答2:


Try this:

SELECT t2.LETTER_ID, t1.YEAR, t1.TIMESTAMP
  FROM (SELECT YEAR, MAX(TIMESTAMP) as MAX_TIMESTAMP
          FROM YOUR_TABLE -- change the table name to yours
         GROUP BY YEAR)t1
  JOIN YOUR_TABLE t2 -- change the table name to yours
    ON t2.YEAR = t1.YEAR
   AND t2.TIMESTAMP = MAX_TIMESTAMP

This query will run on any database.




回答3:


Another method:

SELECT DISTINCT
       letter_id
      ,year
      ,MAX("TIMESTAMP") OVER (PARTITION BY letter_id, year) AS "TIMESTAMP"
FROM   my_data;

Note that TIMESTAMP is a reserved word in Oracle so I assume your column needs to be delimited as "TIMESTAMP".



来源:https://stackoverflow.com/questions/27011494/group-by-with-maxtimestamp

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