Get top 1 row of each group

后端 未结 20 3460
余生分开走
余生分开走 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:14

    This solution can be used to get the TOP N most recent rows for each partition (in the example, N is 1 in the WHERE statement and partition is doc_id):

    SELECT T.doc_id, T.status, T.date_created FROM 
    (
        SELECT a.*, ROW_NUMBER() OVER (PARTITION BY doc_id ORDER BY date_created DESC) AS rnk FROM doc a
    ) T
    WHERE T.rnk = 1;
    

提交回复
热议问题