选择上一条记录并替换值(如果存在)

时间:2014-01-24 09:08:58

标签: sql sql-server-ce

假设我有人和他们的关系状态的记录。我还有一张桌子,我选择给这些人自己的名字。像这样:

Statuses                                  Names
ID | Name | Status   | Date               ID | Name
---------------------------------         -------------
01 | Lisa | Divorced | 2013-01-01         01 | Lizzza
02 | John | Married  | 2013-04-04         03 | Alex
01 | Lisa | Married  | 2013-05-05
01 | Lisa | Single   | 2014-01-23
02 | John | Single   | 2014-01-24

我现在想为每个人选择最后一个状态,在此列表中我还希望看到列表中包含姓名的人,即使他们不在状态表中。在上面的场景中,我希望得到这样的结果:

ID | Name   | Status | Date
---------------------------------
01 | Lizzza | Single | 2014-01-23
02 | John   | Single | 2014-01-24
03 | Alex   | NULL   | NULL

我昨天在这个帖子上提出了类似的问题; Select from other table if value exist但此查询将为我提供完整的状态列表。这次我只想要最后的已知记录而不是所有记录。

快速编辑,我正在使用SQL Compact / SQL CE

3 个答案:

答案 0 :(得分:0)

SELECT * FROM 
(
SELECT * 
    , ROW_NUMBER() OVER (PARTITION BY Name ORDER BY [Date] DESC) AS rn
FROM TableName
)Q
WHERE rn = 1

答案 1 :(得分:0)

select n.id,n.name,s.status,s.date from name n
left outer join statuses s on n.id=s.id and 
s.date =(select max(date) from statuses st where st.id=n.id )

答案 2 :(得分:0)

WITH e AS
(
     SELECT *,
         ROW_NUMBER() OVER
         (
             PARTITION BY ID
             ORDER BY CONVERT(datetime, [Date], 101) DESC
         ) AS Recency
     FROM [Statuses]
)
SELECT e.*, n.name
FROM e left outer join names n  on e.id=n.id 
WHERE Recency = 1