Get the latest date for each record

前端 未结 4 1420
春和景丽
春和景丽 2021-01-25 02:46

I have a History table (like a log) that records changes to parts:

TransactionID    Part ID          Description        Last Updated
1                1                   


        
4条回答
  •  太阳男子
    2021-01-25 03:28

    SELECT TransactionID
          ,PartID
          ,[Description]
          ,[Last Updated]
    FROM (
        SELECT TransactionID
              ,PartID
              ,[Description]
              ,[Last Updated]
              ,ROW_NUMBER() OVER (PARTITION BY [PartID] ORDER BY [Last Updated] DESC) RN 
        FROM TableName
        )A
    WHERE A.RN = 1
    

    Or you can use CTE

    ;WITH CTE AS
      (
        SELECT TransactionID
              ,PartID
              ,[Description]
              ,[Last Updated]
              ,ROW_NUMBER() OVER (PARTITION BY [PartID] ORDER BY [Last Updated] DESC) RN 
        FROM TableName
      )
    SELECT TransactionID
          ,PartID
          ,[Description]
          ,[Last Updated]  
    FROM CTE 
    WHERE A.RN = 1
    

提交回复
热议问题