Select distinct where date is max

家住魔仙堡 提交于 2020-01-06 04:03:27

问题


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


来源:https://stackoverflow.com/questions/21676273/select-distinct-where-date-is-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!