SQL Server Selecting Records with most recent date time

前端 未结 2 1431
后悔当初
后悔当初 2021-02-13 20:26

I have a table as below:

MyJob|   MyKey  |MyCode|MyDate| MyTime 
----------------------------------       
q183b| 0131081a |  24  |100315| 9:37        
q183b| 01         


        
2条回答
  •  长情又很酷
    2021-02-13 20:35

    First combine the date + time columns into a datetime so it's easy to order them. It's been a while since I used Sql Server, but the row_number() function and partitioning is an easy way to find the max of one column grouped by another - the partition clause is similar to a group by.

    select t.* 
    from
    (
        select t.MyKey, t.MyDateTime
        , row_number() over 
             (partition by t.mykey order by t.MyDateTime desc) as keyOrderNbr
        from table t
    ) A
    inner join table t
        on A.MyKey = t.MyKey 
        and A.MyDateTime = t.MyDateTime
    where A.keyOrderNbr = 1
    

提交回复
热议问题