简体   繁体   中英

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM