Create a SQL query to retrieve most recent records

前端 未结 4 2167
暗喜
暗喜 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: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.

提交回复
热议问题