Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsql -group by by max datetime in rows

Tags:

tsql

I have a table and it's data looks like this:

 id         name       date
 ---------  ---------  ----------
 1          a          2012-08-30 10:36:27.393
 1          b          2012-08-30 14:36:27.393
 2          c          2012-08-30 13:36:27.393
 2          d          2012-08-30 16:36:27.393

I retrieve the max datetime with this query:

SELECT id,Max(date) as mymaxdate
FROM table1
group by id

This query givse me two rows like this:

1     2012-08-30 14:36:27.393
2     2012-08-30 16:36:27.393

It's correct, but how can i change it to retrieve this result?

1   b  2012-08-30 14:36:27.393
2   d  2012-08-30 16:36:27.393

Thanks

like image 722
motevalizadeh Avatar asked Dec 27 '22 18:12

motevalizadeh


2 Answers

For SQL Server 2005+

WITH cteMaxDate AS (
    SELECT id, name, date, 
           ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC) AS RowNum
        FROM table1
)
SELECT id, name, date
    FROM cteMaxDate
    WHERE RowNum = 1;
like image 146
Joe Stefanelli Avatar answered Mar 11 '23 11:03

Joe Stefanelli


One of the options:

select 
    t1.id
    ,t1.name
    ,t1.date 
from 
    table1 t1
    inner join (
        SELECT id,Max(date) as mymaxdate
        FROM table1
        group by id
    ) mt1
        on t1.id = mt1.id
        and t1.date = mt1.mymaxdate
like image 26
kristof Avatar answered Mar 11 '23 11:03

kristof