我现在有一个表A,里面有两个字段 姓名 和 日期 姓名 日期
张三 2009-01-01张三 2010-10-10李四 2010-1-10我现在想查询出的结果是 去掉重复的姓名保留一个日期为最新的姓名
如:
姓名 日期
张三 2010-10-10李四 2010-1-10请问查询语该如何写 谢谢
张三 2009-01-01张三 2010-10-10李四 2010-1-10我现在想查询出的结果是 去掉重复的姓名保留一个日期为最新的姓名
如:
姓名 日期
张三 2010-10-10李四 2010-1-10请问查询语该如何写 谢谢
from tb t
where not exists(select 1
from tb
where 姓名=t.姓名 and 日期>t.日期)
from A t
where not exists(select 1 from A where 姓名=t.姓名 and 日期>t.日期)
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
*/
where not exists(select null from tb where t.姓名 =姓名 and 日期>t.日期)
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 行)
*/