选择不同的日期最大值

时间:2014-02-10 11:43:59

标签: sql sql-server-ce sql-date-functions sqldatetime

这感觉真的很愚蠢,但我不能在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

即,选择日期最高的不同id:s,并加入名称。作为奖励,对列表进行排序,使最新记录显示在最佳状态。

2 个答案:

答案 0 :(得分: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表的过滤器。

答案 1 :(得分: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);