我现在有一个表A,里面有两个字段 姓名 和 日期 姓名   日期
张三   2009-01-01张三   2010-10-10李四   2010-1-10我现在想查询出的结果是 去掉重复的姓名保留一个日期为最新的姓名
如:
姓名   日期
张三   2010-10-10李四   2010-1-10请问查询语该如何写 谢谢

解决方案 »

  1.   

    select 姓名 , max(日期) 日期 from a group by 姓名
      

  2.   

    select *
    from tb t
    where not exists(select 1
                     from tb
                     where 姓名=t.姓名 and  日期>t.日期)
      

  3.   

    select * 
    from A t
    where not exists(select 1 from A where 姓名=t.姓名 and 日期>t.日期)
      

  4.   

    --> 测试数据:#
    if object_id('tempdb.dbo.#') is not null drop table #
    create table #(姓名 varchar(8), 日期 datetime)
    insert into #
    select '张三', '2009-01-01' union all
    select '张三', '2010-10-10' union all
    select '李四', '2010-1-10'select * from # t where not exists (select 1 from # where 姓名=t.姓名 and 日期>t.日期)/*
    姓名       日期
    -------- -----------------------
    张三       2010-10-10 00:00:00.000
    李四       2010-01-10 00:00:00.000
    */
      

  5.   

    select * from tb t
    where not exists(select null from tb where t.姓名 =姓名  and 日期>t.日期)
      

  6.   

    create table a(姓名 varchar(10),日期 datetime)
    insert into a values('张三', '2009-01-01')
    insert into a values('张三', '2010-10-10')
    insert into a values('李四', '2010-1-10')
    go--如果只有这两个字段,直接分组取max即可。
    select 姓名 , max(日期) 日期 from a group by 姓名--如果不止这两个字段,用not exists
    select t.* from a t where not exists(select 1 from a where 姓名 = t.姓名 and 日期 > t.日期)
    select t.* from a t where 日期 = (select max(日期) from a where 姓名 = t.姓名)drop table a/*姓名         日期                                                     
    ---------- ------------------------------------------------------ 
    李四         2010-01-10 00:00:00.000
    张三         2010-10-10 00:00:00.000(所影响的行数为 2 行)姓名         日期                                                     
    ---------- ------------------------------------------------------ 
    张三         2010-10-10 00:00:00.000
    李四         2010-01-10 00:00:00.000(所影响的行数为 2 行)姓名         日期                                                     
    ---------- ------------------------------------------------------ 
    张三         2010-10-10 00:00:00.000
    李四         2010-01-10 00:00:00.000(所影响的行数为 2 行)
    */
      

  7.   

    用group by时,要select出其他字段时,也可以尝试对其他字段使用max函数,或其他聚合函数
      

  8.   

    select 姓名,max(日期)as 日期 from A group by 姓名
      

  9.   

    水哥的改进下 select distinct * from......