创建SQL查询以检索最新记录

时间:2009-06-26 15:18:44

标签: sql tsql derived-table

我正在为我的项目团队创建一个状态板模块。状态板允许用户将其状态设置为输入或输出,并且还可以提供注释。我打算将所有信息存储在一个表中......以下是数据示例:

Date               User         Status    Notes
-------------------------------------------------------
1/8/2009 12:00pm   B.Sisko      In        Out to lunch    
1/8/2009 8:00am    B.Sisko      In  
1/7/2009 5:00pm    B.Sisko      In    
1/7/2009 8:00am    B.Sisko      In    
1/7/2009 8:00am    K.Janeway    In   
1/5/2009 8:00am    K.Janeway    In    
1/1/2009 8:00am    J.Picard     Out       Vacation  

我想查询数据并返回每个用户的最新状态,在这种情况下,我的查询将返回以下结果:

Date               User         Status    Notes
-------------------------------------------------------  
1/8/2009 12:00pm   B.Sisko      In        Out to lunch    
1/7/2009 8:00am    K.Janeway    In   
1/1/2009 8:00am    J.Picard     Out       Vacation  

我试图找出TRANSACT-SQL来实现这一目标?任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:71)

子查询派生表中聚合,然后加入它。

 Select Date, User, Status, Notes 
    from [SOMETABLE]
    inner join 
    (
        Select max(Date) as LatestDate, [User]
        from [SOMETABLE]
        Group by User
    ) SubMax 
    on [SOMETABLE].Date = SubMax.LatestDate
    and [SOMETABLE].User = SubMax.User 

答案 1 :(得分:56)

另一种方法是,如果使用子查询

,这将只扫描一次而不是两次

仅限sql server 2005及以上

select Date, User, Status, Notes 
from (
       select m.*, row_number() over (partition by user order by Date desc) as rn
       from [SOMETABLE] m
     ) m2
where m2.rn = 1;

答案 2 :(得分:9)

派生表可行,但如果这是SQL 2005,则CTE和ROW_NUMBER可能更清晰:

WITH UserStatus (User, Date, Status, Notes, Ord)
as
(
SELECT Date, User, Status, Notes, 
     ROW_NUMBER() OVER (PARTITION BY User ORDER BY Date DESC)
FROM [SOMETABLE]
)

SELECT User, Date, Status, Notes from UserStatus where Ord = 1

这也有助于显示每个用户的最新x状态。

答案 3 :(得分:5)

另一种简单方法:

SELECT Date, User, Status, Notes  
FROM Test_Most_Recent 
WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)

答案 4 :(得分:0)

为每条记录添加一个自动递增的主键,例如 UserStatusId。

那么您的查询可能如下所示:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

日期用户状态说明