how to use SQL group to filter rows with maximum date value

NewtonCode picture NewtonCode · Jun 10, 2014 · Viewed 26.7k times · Source

I have the following table

CREATE TABLE Test
    (`Id` int, `value` varchar(20), `adate` varchar(20))
;

INSERT INTO Test
    (`Id`, `value`, `adate`)
VALUES
    (1, 100, '2014-01-01'),
    (1, 200, '2014-01-02'),
    (1, 300, '2014-01-03'),
    (2, 200, '2014-01-01'),
    (2, 400, '2014-01-02'),
    (2, 30 , '2014-01-04'),
    (3, 800, '2014-01-01'),
    (3, 300, '2014-01-02'),
    (3, 60 , '2014-01-04')
;

I want to achieve the result which selects only Id having max value of date. ie

Id ,value ,adate

 1, 300,'2014-01-03'     
 2, 30 ,'2014-01-04'     
 3, 60 ,'2014-01-04'

how can I achieve this using group by? I have done as follows but it is not working.

Select Id,value,adate
from Test
group by Id,value,adate
having adate = MAX(adate)

Can someone help with the query?

Answer

Mike Sherrill 'Cat Recall' picture Mike Sherrill 'Cat Recall' · Jun 10, 2014

Select the maximum dates for each id.

select id, max(adate) max_date
from test
group by id

Join on that to get the rest of the columns.

select t1.*
from test t1
inner join (select id, max(adate) max_date
            from test
            group by id) t2
on t1.id = t2.id and t1.adate = t2.max_date;