SQL Server Selecting Records with most recent date time

前端 未结 2 1423
后悔当初
后悔当初 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: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.

提交回复
热议问题