Get the latest date for each record

前端 未结 4 1417
春和景丽
春和景丽 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:24

    Here's How I would do it

     ;WITH CTE AS 
     (
     Select PartId, MAX(LASTUPDATED) as 'MAXX' from part group by PartId
     ) 
     Select TransActionId, p.PartId, Description, p.LASTUPDATED
     from Part p
     inner join CTE on p.LastUpdated = CTE.MAXX
                    and p.PartId = CTE.PartId           
    
    0 讨论(0)
  • 2021-01-25 03:25
    SELECT t.TransactionID, t.PartID, t.Description, t.LastUpdated
    FROM History t
    JOIN (SELECT PartID, MAX(TransactionID)
    FROM History
    GROUP BY PartID) t2 ON t.PartID = t2.PartID
    AND t.TransactionID = t2.TransactionID
    

    will also work.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-25 03:34
    select 
        TransactionID, PartID, Description, LastUpdated
    from 
        History H
    where
        LastUpdated = 
        (
            select 
                max(LastUpdated) 
            from 
                History
            where
                PartID = H.PartID
        )
    
    0 讨论(0)
提交回复
热议问题