表构成  : 记录id,用户id,任职开始时间,任职结束时间,职务。
一个用户可以有多条任职记录,最新那条为当前任职记录要找出所有用户或某个用户最新的那条也就是当前的任职记录,这个SQL 查询该什么写呢

解决方案 »

  1.   

    本帖最后由 libin_ftsafe 于 2010-01-05 18:52:14 编辑
      

  2.   

    select 
        t.* 
    from 
        表 t 
    where 
        任职开始时间=(select MAX(任职开始时间) from 表 where 用户id=t.用户id )
      

  3.   

    select 
        * 
    from 
        tb t 
    where 
       任职开始时间=(select max(任职开始时间) from t where 用户id=t.用户id )
      

  4.   

    select 
        * 
    from 
        tb t 
    where 
       任职开始时间=(select max(任职开始时间) from tb where 用户id=t.用户id )
      

  5.   


    create proc sp_test
    @userId int
    as
    select 
        t.* 
    from 
        表 t 
    where 
        not exists(select 1 from 表 where 用户id=t.用户id and 任职开始时间>t.任职开始时间)
    And(t.userid=@userid or isnull(@userid,'')='')
      

  6.   

    以4楼为例 
    子查询
    select max(任职开始时间) from tb where 用户id=t.用户id
    与外面tb表本身对比
    查询出用户ID相同 任职开始时间最大的记录
      

  7.   

    --1
    select t.* from tb t where 任职开始时间 = (select max(任职开始时间) from tb where 用户id = t.用户id)--2
    select t.* from tb t where not exists(select 1 from tb where tb where 用户id = t.用户id and 任职开始时间 > t.任职开始时间)--3
    --这个你应该能看懂了.
    select m.* from tb m,
    (select 用户id , max(任职开始时间) 任职开始时间 from tb group by 用户id) n
    where m.用户id  = n.用户id  and m.任职开始时间 = n.任职开始时间实际上1,2和3的意思是一样的.
      

  8.   

    参考N=1的情况http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
    分组取最大N条记录方法
      

  9.   

    采用not exists那个方法的话,不知道会不会遇到过这种问题(我是在oracle下使用),如果任职开始时间 > t.任职开始时间(为null),则这条null的记录也会被筛选出来。不知道sql-server是否有这个问题,我的解决方法最后在条件里过滤掉时间为null的记录了。建议楼主注意下。推荐用not exists方法,比max方法快很多