Select distinct where date is max

2019-08-11 05:26发布

问题:

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.

回答1:

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.



回答2:

Use the following query:

SELECT U.Id AS Id, U.Name AS Name, S.thedate AS Date, S.status AS Status
FROM Statuses S
INNER JOIN Users U on S.id = U.id
WHERE S.thedate IN (
         SELECT MAX(thedate)
         FROM statuses
         GROUP BY id);