79

我正在为我的项目团队创建一个状态板模块。状态板允许用户将他们的状态设置为进入或退出,他们还可以提供注释。我计划将所有信息存储在一个表中......数据示例如下:

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 来实现这一点?任何帮助,将不胜感激。

4

5 回答 5

91

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

 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 
于 2009-06-26T15:23:01.470 回答
82

另一种方式,如果您使用子查询,这将只扫描一次表而不是两次

仅限 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;
于 2009-06-26T15:41:30.437 回答
12

派生表可以工作,但如果这是 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 状态。

于 2009-06-26T18:24:14.143 回答
6

另一种简单的方法:

SELECT Date, User, Status, Notes  
FROM Test_Most_Recent 
WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)
于 2012-07-12T07:20:24.370 回答
0

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

然后您的查询可能如下所示:

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

日期 用户状态 备注

于 2020-12-20T04:21:12.427 回答