Create a SQL query to retrieve most recent records

前端 未结 4 2160
暗喜
暗喜 2020-11-29 20:46

I am creating a status board module for my project team. The status board allows the user to to set their status as in or out and they can also provide a note. I was plannin

相关标签:
4条回答
  • 2020-11-29 21:20

    Another easy way:

    SELECT Date, User, Status, Notes  
    FROM Test_Most_Recent 
    WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)
    
    0 讨论(0)
  • 2020-11-29 21:27

    another way, this will scan the table only once instead of twice if you use a subquery

    only sql server 2005 and up

    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;
    
    0 讨论(0)
  • 2020-11-29 21:33

    The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:

    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
    

    This would also facilitate the display of the most recent x statuses from each user.

    0 讨论(0)
  • 2020-11-29 21:34

    Aggregate in a subquery derived table and then join to it.

     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 
    
    0 讨论(0)
提交回复
热议问题