sqlgreatest-n-per-group

how do I query sql for a latest record date for each user


I have a table that is a collection entries as to when a user was logged on.

username, date,      value
--------------------------
brad,     1/2/2010,  1.1
fred,     1/3/2010,  1.0
bob,      8/4/2009,  1.5
brad,     2/2/2010,  1.2
fred,     12/2/2009, 1.3

etc..

How do I create a query that would give me the latest date for each user?

Update: I forgot that I needed to have a value that goes along with the latest date.


Solution

  • This is the simple old school approach that works with almost any db engine, but you have to watch out for duplicates:

    select t.username, t.date, t.value
    from MyTable t
    inner join (
        select username, max(date) as MaxDate
        from MyTable
        group by username
    ) tm on t.username = tm.username and t.date = tm.MaxDate
    

    Using window functions will avoid any possible issues with duplicate records due to duplicate date values, so if your db engine allows it you can do something like this:

    select x.username, x.date, x.value 
    from (
        select username, date, value,
            row_number() over (partition by username order by date desc) as _rn
        from MyTable 
    ) x
    where x._rn = 1