现在有员工信息表   tb
字段:姓名 编号 部门名称 调入时间现在有这样的需求,一员工调入某个部门时产生一条记录,某个月后因需要调入另一个部门,这时候又产生一条记录,我想得到当前所有员工所在部门的查询结果,每个员工离当前日期最近的一条信息。
效果如下
原数据姓名  编号  部门   调入时间
张三  001   A部    2010-01-01
张三  001   B部    2010-02-01
张三  001   A部    2010-03-01
张三  001   B部    2010-04-01
李四  002   C部    2010-01-01
王五  003   D部    2010-01-01
王五  003   H部    2010-02-01
查询结果如下姓名  编号  部门   调入时间
张三  001   B部    2010-04-01
李四  002   C部    2010-01-01
王五  003   H部    2010-02-01

解决方案 »

  1.   

    select *
    from tb t
    where not exists(select 1
                     from tb
                     where 姓名=t.姓名 and 调入时间>t.调入时间)
      

  2.   

    select * from tb t
    where 调入时间=(select max(调入时间) from tb where 姓名=t.姓名 and 编号=t.编号)
      

  3.   

    select 姓名,编号,部门,调入时间
    from
    (select *,rn=row_number()over(partition by 姓名,编号 order by 调入时间 desc) from tb)t
    where rn=1
      

  4.   

    select t.* from tb t where 调入时间 = (select max(调入时间) from tb where 编号 = t.编号)select t.* from tb t where not exists (select 1 from tb where 编号 = t.编号 and 调入时间 > t.调入时间)
      

  5.   

    select 姓名,编号,部门,调入时间
    from
    (select *,rn=row_number()over(partition by 姓名,编号 order by 调入时间 desc) from tb)t
    where rn=1
      

  6.   


    select t.* from tb t 
    where not exists 
    (select 1 from tb where 编号 = t.编号 and 姓名=t.姓名 and 调入时间 > t.调入时间)
      

  7.   

    select t1.姓名,t1.编号,t2.部门,t1.调入时间
    from 
    (select 姓名,编号,max(调入时间) as 调入时间 from tb) t1,tb t2
    where t1.编号 = t2.编号 and t1.姓名=t2.姓名
      

  8.   


    --自己挑吧
    --1
    select t.* from tb t 
    where not exists 
    (select 1 from tb where 编号 = t.编号 and 姓名=t.姓名 and 调入时间 > t.调入时间)--2
    select * from tb t
    where 调入时间=(select max(调入时间) from tb where 姓名=t.姓名 and 编号=t.编号)--3
    select 姓名,编号,部门,调入时间
    from
    (select *,rn=row_number()over(partition by 姓名,编号 order by 调入时间 desc) from tb)t
    where rn=1--4
    select t1.姓名,t1.编号,t2.部门,t1.调入时间
    from 
    (select 姓名,编号,max(调入时间) as 调入时间 from tb) t1,tb t2
    where t1.编号 = t2.编号 and t1.姓名=t2.姓名
      

  9.   

    首先说明: 这个记录表的记录没有ID, 因此查询起来, 其效率肯定收到影响, 但是结果肯定没有问题:select t1.*
    from tb as t1, (select 编号,max(调入时间) as 调入时间 from tb group by 编号) t2
    where t1.编号 = t2.编号 and t1.调入时间 = t2.调入时间