Select Most Recent States From History Table

后端 未结 5 956
栀梦
栀梦 2021-02-08 13:27

I have inherited a table with a structure something like this:

ID   Name   Timestamp   Data
----------------------------
1    A      40          ...
2    A               


        
5条回答
  •  忘掉有多难
    2021-02-08 14:06

    If you are using SQL Server 2005/2008, then the CTE solution already listed by Mitch Weat is the best from a performance perspective. However, if you are using SQL Server 2000, then you can't assume there aren't duplicate Name | TimeStamp combinations. Use the following code to return only one record per name:

    SELECT ID
        , Name
        , TimeStamp
        , Data
    FROM DataTable dt
    INNER JOIN
        (SELECT Name
        , MIN(DataTable.ID) AS MinimumID
    FROM DataTable  
    INNER JOIN  
        (SELECT Name
            , MAX(Timestamp) AS Timestamp 
        FROM DataTable 
        GROUP BY Name) latest 
        ON DataTable.Name = Latest.Name
        AND DataTable.Timestamp = Latest.Timestamp
    GROUP BY Name) MinimumLatest
    ON dt.ID = MinimumLatest.ID
    

    So if you add another record like 9 C 30, then this will only return ID 6. If you don't go this far, then you may end up return 9 C 30 and 6 C 30.

提交回复
热议问题