在SQL Server中获取上次修改的记录

时间:2015-04-09 02:44:42

标签: sql sql-server

我有一个包含这些值的表

ID, Name  , LastModifedDate
1 , Tom   , 01/01/2014
1 , Romain, 04/01/2014
2 , Paul  , 01/01/2014
3 , John  , 02/01/2014

我需要获得如下的最新记录

1, Romain, 04/01/2014 
2, Paul    01/01/2014
3, John,   02/01/2014 

3 个答案:

答案 0 :(得分:4)

您可以使用row_numberID

选择上次修改的行
select * from (
    select *, 
        row_number() over (partition by ID order by LastModifiedDate desc) rn
    from mytable
) t1 where rn = 1

答案 1 :(得分:0)

    declare @t table (Id int,name varchar(10),lasmodified date)
    insert into @t(Id,name,lasmodified) values (1,'tom','01/01/2014'),
    (1,'Romain','04/01/2014'),(2,'paul','01/01/2014'),(3,'john','02/01/2014')

 ;with  cte as 
    (select ID,name,lasmodified,row_number()OVER(PARTITION BY ID order by lasmodified   desc) RN from @t)

    select ID,name,MAX(CONVERT(VARCHAR(20),lasmodified,103)) from cte 
    WHERE RN = 1
    group by ID,name 
order by name desc

答案 2 :(得分:0)

你的意思是自2月1日以来的所有记录吗?保罗为什么要被选中而不是汤姆?

SELECT ID, Name, LastModifiedDate
FROM YourTable
where LastModifiedDate > '01/01/2014'

或者你想要最后三个?

SELECT TOP 3 ID, Name, LastModifiedDate
FROM YourTable
order by LastModifiedDate desc