2014-02-10 80 views
1

這種感覺真的很愚蠢的問,但我不能在SQL Server精簡(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 

也就是說,選擇不同編號:s其中的日期是最高的,並加入名稱。作爲獎勵,對列表進行排序,以便最新的記錄處於最佳狀態。

回答

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表中的過濾器。

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