Get top 1 row of each group

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

    If you're worried about performance, you can also do this with MAX():

    SELECT *
    FROM DocumentStatusLogs D
    WHERE DateCreated = (SELECT MAX(DateCreated) FROM DocumentStatusLogs WHERE ID = D.ID)
    

    ROW_NUMBER() requires a sort of all the rows in your SELECT statement, whereas MAX does not. Should drastically speed up your query.

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

    Try this:

    SELECT [DocumentID]
        ,[tmpRez].value('/x[2]', 'varchar(20)') AS [Status]
        ,[tmpRez].value('/x[3]', 'datetime') AS [DateCreated]
    FROM (
        SELECT [DocumentID]
            ,cast('<x>' + max(cast([ID] AS VARCHAR(10)) + '</x><x>' + [Status] + '</x><x>' + cast([DateCreated] AS VARCHAR(20))) + '</x>' AS XML) AS [tmpRez]
        FROM DocumentStatusLogs
        GROUP BY DocumentID
        ) AS [tmpQry]
    
    0 讨论(0)
提交回复
热议问题