create table #t1 (id int, status varchar(10), tme time)insert into #t1 select 1,'started','07:00' union allselect 1,'running','08:00' union allselect 1,'completed','09:00' union allselect 2,'started','10:00' union allselect 2,'running','11:00';with ctsas (select id,max(tme) tm from #t1group by id)select a.* from #t1 a inner join cts b on a.id=b.id and tm=tmeorder by a.id
declare @sometable table (ID int, Status nvarchar(50), [time] datetime)insert into @sometable values (1,'Started','2012-02-02 07:00'),(1,'Running','2012-02-02 08:30'),(1,'Completed','2012-02-02 09:30'),(2,'Started','2012-02-02 04:15'),(2,'Running','2012-02-02 05:00');with cte as(SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY DT DESC) AS RowNum, *FROM @SomeTable)SELECT ID, Status, TimeFROM CTEWHERE RowNum = 1ORDER BY ID
SELECT t1.ID, t1.Status, t1.TimeFROM @sometable t1INNER JOIN ( SELECT ID, MAX(Time) as maxtime FROM @sometable t2 GROUP BY ID ) as dev1 ON t1.ID = dev1.ID AND t1.time = dev1.maxtimeORDER BY 1