Search code examples
sqlsql-server-cesql-date-functionssqldatetime

Select distinct where date is max


This feels really stupid to ask, but i can't do this selection in SQL Server Compact (CE)

If i have two tables like this:

Statuses                      Users
id | status   | thedate        id | name
-------------------------      -----------------------
0  | Single   | 2014-01-01     0  | Lisa
0  | Engaged  | 2014-01-02     1  | John
1  | Single   | 2014-01-03
0  | Divorced | 2014-01-04

How can i now select the latest status for each person in statuses? the result should be:

Id | Name | Date       | Status
--------------------------------
0  | Lisa | 2014-01-04 | Divorced
1  | John | 2014-01-03 | Single

that is, select distinct id:s where the date is the highest, and join the name. As bonus, sort the list so the latest record is on top.


Solution

  • In SQL Server CE, you can do this using a join:

    select u.id, u.name, s.thedate, s.status
    from users u join
         statuses s
         on u.id = s.id join
         (select id, max(thedate) as mtd
          from statuses
          group by id
         ) as maxs
         on s.id = maxs.id and s.thedate = maxs.mtd;
    

    The subquery calculates the maximum date and uses that as a filter for the statuses table.