Skip to content
Advertisement

Oracle max function on timestamp datatype

I want to take a max date from a timestamp datatype in oracle

my data look like this

id  updated_date
--  -------------------
1   2011-12-21 10:34:24 
1   2011-12-21 09:52:15
1   2011-12-21 10:02:49

Since all the date are same but timestamp is difference the max function bringing all the 3 rows instead i want to see the max date with latest timestamp for each ID like below

Select MAX(updated_date) update_date, id FROM id_table group by id;
id  updated_date
--  -------------------
1   2011-12-21 10:34:24 

thanks in advance

The table as 10000 plus rows, the data looks like below

 id  updated_date
 --  -------------------
 1   2011-12-21 10:34:24 
 1   2011-12-21 09:52:15
 1   2011-12-21 10:02:49
 2   2011-13-21 10:34:24 
 2   2011-13-21 09:52:15
 2   2011-13-21 10:02:49
 3   2011-14-21 10:34:24 
 3   2011-14-21 09:52:15
 3   2011-14-21 10:02:49

On select i want to see 1 row per id no duplicates Select MAX(updated_date) update_date, id FROM id_table group by id;

id  updated_date
 --  -------------------
 1   2011-12-21 10:34:24 
 2   2011-13-21 10:34:24 
 3   2011-14-21 10:34:24 

Advertisement

Answer

You may use the FIRST aggregate function or row_number().

1.

SELECT MAX(id) KEEP(DENSE_RANK FIRST ORDER BY updated_date DESC) AS id,
       MAX(updated_date) update_date
FROM id_table;

2.

SELECT id,
       updated_date
FROM (
     SELECT i.*,
            ROW_NUMBER() OVER(
                 ORDER BY updated_date DESC
            ) AS rn
     FROM id_table i
)
WHERE rn = 1;

Demo

Bonus ( for Oracle 12c and above) :

select * from id_table 
ORDER BY updated_date DESC FETCH FIRST 1 ROWS ONLY
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement