1

问这个感觉真的很愚蠢,但我无法在 SQL Server Compact (CE) 中进行此选择

如果我有两个这样的表:

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

我现在如何为状态中的每个人选择最新状态?结果应该是:

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

即选择日期最高的distinct id:s,并加入名称。作为奖励,对列表进行排序,以便最新记录位于顶部。

4

2 回答 2

0

在 SQL Server CE 中,您可以使用以下命令执行此操作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;

子查询计算最大日期并将其用作statuses表的过滤器。

于 2014-02-10T11:50:46.237 回答
0

使用以下查询:

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);
于 2014-02-10T11:55:12.093 回答