创建一个SQL查询来获取最近的记录创建一个SQL查询来获取最近的记录(Create a SQL qu

2019-05-13 22:47发布

我创建了我的项目团队状态板模块。 状态板允许用户设置自己的地位或缩小,他们也可以提供一个音符。 我打算存储在单个表中的所有信息......,并遵循示例中的数据:

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

Answer 1:

总结在一个子查询派生表,然后连接到这里。

 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 


Answer 2:

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

只有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;


Answer 3:

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



Answer 4:

另一个简单的方法:

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


文章来源: Create a SQL query to retrieve most recent records