Get top 1 row of each group

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

    SELECT * FROM
    DocumentStatusLogs JOIN (
      SELECT DocumentID, MAX(DateCreated) DateCreated
      FROM DocumentStatusLogs
      GROUP BY DocumentID
      ) max_date USING (DocumentID, DateCreated)
    

    What database server? This code doesn't work on all of them.

    Regarding the second half of your question, it seems reasonable to me to include the status as a column. You can leave DocumentStatusLogs as a log, but still store the latest info in the main table.

    BTW, if you already have the DateCreated column in the Documents table you can just join DocumentStatusLogs using that (as long as DateCreated is unique in DocumentStatusLogs).

    Edit: MsSQL does not support USING, so change it to:

    ON DocumentStatusLogs.DocumentID = max_date.DocumentID AND DocumentStatusLogs.DateCreated = max_date.DateCreated
    

提交回复
热议问题