Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Selecting Records with most recent date time

Tags:

sql

I have a table as below:

MyJob|   MyKey  |MyCode|MyDate| MyTime 
----------------------------------       
q183b| 0131081a |  24  |100315| 9:37        
q183b| 0131081a |  9   |100315| 11:38        
q183b| 0132426a |  1   |90314 | 15:36        
q183b| 0132426a |  2   |100315| 9:36        
q183b| 0132426a |  85  |100315| 11:36

Note that MyDate format will be YYMMDD and MyTime is in 24 hour format.

I want to return the result of unique MyKey with most recent MyDate and MyTime. The expected result will be something like:

MyJob |   MyKey  |MyCode| MyDate | MyTime        
q183b | 0131081a | 9    | 100315 | 11:38        
q183b | 0132426a | 85   | 100315 | 11:36

Any help will be much appreciated. Thanks.

like image 667
user2709309 Avatar asked Aug 23 '13 01:08

user2709309


People also ask

How do I get the latest timestamp record in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How do I select a timestamp in SQL?

The CURRENT_TIMESTAMP function returns the current date and time, in a 'YYYY-MM-DD hh:mm:ss. mmm' format. Tip: Also look at the GETDATE() function.

Is there a LastIndexOf in SQL Server?

No, SQL server doesnt have LastIndexOf.


1 Answers

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
like image 178
Jeff Scott Avatar answered Sep 19 '22 12:09

Jeff Scott