Get top 1 row of each group

后端 未结 20 3047
余生分开走
余生分开走 2020-11-21 04:42

I have a table which I want to get the latest entry for each group. Here\'s the table:

DocumentStatusLogs Table

|ID| DocumentID | Status         


        
20条回答
  •  你的背包
    2020-11-21 05:15

    This is one of the most easily found question on the topic, so I wanted to give a modern answer to the it (both for my reference and to help others out). By using first_value and over you can make short work of the above query:

    Select distinct DocumentID
      , first_value(status) over (partition by DocumentID order by DateCreated Desc) as Status
      , first_value(DateCreated) over (partition by DocumentID order by DateCreated Desc) as DateCreated
    From DocumentStatusLogs
    

    This should work in Sql Server 2008 and up. First_value can be thought of as a way to accomplish Select Top 1 when using an over clause. Over allows grouping in the select list so instead of writing nested subqueries (like many of the existing answers do), this does it in a more readable fashion. Hope this helps.

提交回复
热议问题