现有一个数据库,名字为test里面有3个字段,id为自动,name为字符串,time为时间表内数据有4条id     name      time
1      张三      2010-02-02 10:15:23
2      张三      2011-02-02 10:15:32
3      张三      2012-02-02 10:15:46
4      李四      2012-02-02 10:15:53
想要通过sql语句查询该数据库,查询出的结果要是id     name      time
3      张三      2012-02-02 10:15:46
4      李四      2012-02-02 10:15:53也就是过滤掉name相同的,并取time为最大的结果列出来请问这语句该怎么写呢?网上都是去重复的,不适用于这种需求啊

解决方案 »

  1.   

    select * from test t where not exists(select 1 from test where name=t.name and [time]>t.[time])
      

  2.   

    if object_id('[test]') is not null drop table [test]
    go
    create table [test]([id] int,[name] varchar(4),[time] datetime)
    insert [test]
    select 1,'张三','2010-02-02 10:15:23' union all
    select 2,'张三','2011-02-02 10:15:32' union all
    select 3,'张三','2012-02-02 10:15:46' union all
    select 4,'李四','2012-02-02 10:15:53'select * from [test] t where not exists(select 1 from test where name=t.name and [time]>t.[time])
    /*
    id          name time
    ----------- ---- -----------------------
    3           张三   2012-02-02 10:15:46.000
    4           李四   2012-02-02 10:15:53.000(2 行受影响)*/
      

  3.   

    select * from tb t where time=(select max(time) from tb where name=t.name)