根据列和最新日期

时间:2016-11-24 18:06:38

标签: sql sql-server sql-server-2008

在下表中,我需要获取表的查询以获取删除查询,以根据较旧的加入日期删除唯一员工。

结果应该是唯一的EmpNo,其中Doj是最新的。 以下是表格数据查询

DECLARE @TableTest TABLE (
    [Sid] [int] NULL,
    [EmpNo] [int] NULL,
    [EmpName] [nvarchar](50) NULL,
    [DoJ] [int] NULL
)

INSERT INTO @TableTest VALUES 
 (101,'Suresh',20160517)
,(102,'Ravi',20160312)
,(101,'Ramu',20161022)
,(103,'Kumar',20160308)
,(104,'Gopi',20160411)
,(104,'Sridhar',20160620)
,(104,'Suresh',20161012)

预期结果

Expected result

1 个答案:

答案 0 :(得分:1)

如果要删除行,可以执行以下操作:

with todelete as (
      select tt.*,
             row_number() over (partition by EmpNo order by Sid desc) as seqnum
      from @tabletest
     )
delete from todelete
    where seqnum <> 1;