SQL Server Selecting Records with most recent date time

前端 未结 2 1429
后悔当初
后悔当初 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
    
    0 讨论(0)
  • 2021-02-13 20:43

    Firstly, you will need to convert your date char into a date field so that you can order by it. Then what you can do is:

    SELECT DISTINCT *
    FROM MyTable
    WHERE MyTable.MyDate =
    (
        SELECT MAX(Sub_MyTable.MyDate)
        FROM MyTable 
        WHERE MyTable.MyKey = Sub_MyTable.MyKey
    );
    

    Now remember, the MAX(MyDate) and other references to MyDate won't do what you require unless you turn the field into a date field. I suggest creating your own function to convert the char field into a date field.

    If you try to order by the MyDate field as it is, you will have the results sorted in alphabetical order since it's a string.

    If the time part is important in the results then you can combine the two as suggested by @jeff.

    0 讨论(0)
提交回复
热议问题