我有一个表十多万条记录,其中大约有1万多条记录名字复重了!我本意是名字不可以重复的!
表结构如下:
名字 班级 入学日期
张三 高二 2006-01-01
李四 高三 2003-01-02
李四 高三 2006-08-02
李四 高三 2004-03-03我现在想把这个(名字)重复记录中(入学日期)较旧的记录都删除,只保留(入学日期)较新的一条就可以了!
谢谢大家!
表结构如下:
名字 班级 入学日期
张三 高二 2006-01-01
李四 高三 2003-01-02
李四 高三 2006-08-02
李四 高三 2004-03-03我现在想把这个(名字)重复记录中(入学日期)较旧的记录都删除,只保留(入学日期)较新的一条就可以了!
谢谢大家!
where not exists(select 1 from table where a.名字 = 名字 and 入学日期 < a.入学日期)
insert tb select '张三','高二','2006-01-01'
insert tb select '李四','高三','2003-01-02'
insert tb select '李四','高三','2006-08-02'
insert tb select '李四','高三','2004-03-03'
delete a
from tb a
where exists(select 1
from tb
where a.名字 = 名字 and 入学日期 > a.入学日期) select * from tb
/*
名字 班级 入学日期
------ ------ ------------------------------------------------------
张三 高二 2006-01-01 00:00:00.000
李四 高三 2006-08-02 00:00:00.000*/
drop table tb
create table t1 (
名字 varchar(10),
班级 varchar(10),
入学日期 datetime
)
insert into t1 (名字,班级,入学日期 ) values('张三','高二','2006-01-01')insert into t1 (名字,班级,入学日期 ) values('李四','高三','2003-01-02')insert into t1 (名字,班级,入学日期 ) values('李四','高三','2006-08-02')insert into t1 (名字,班级,入学日期 ) values('李四','高三','2004-03-03')select * from t1/*
名字 班级 入学日期
---------- ---------- ------------------------------------------------------
张三 高二 2006-01-01 00:00:00.000
李四 高三 2003-01-02 00:00:00.000
李四 高三 2006-08-02 00:00:00.000
李四 高三 2004-03-03 00:00:00.000(所影响的行数为 4 行)
*/select *
from t1 a
where not exists(select * from t1 where 名字=a.名字 and 入学日期>a.入学日期)/*
名字 班级 入学日期
---------- ---------- ------------------------------------------------------
张三 高二 2006-01-01 00:00:00.000
李四 高三 2006-08-02 00:00:00.000(所影响的行数为 2 行)
*/
create table sss(名字 char(6),班级 char(6),入学日期 datetime)
insert sss select '张三','高二','2006-01-01'
insert sss select '李四','高三','2003-01-02'
insert sss select '李四','高三','2006-08-02'
insert sss select '李四','高三','2004-03-03'delete sss from sss b
where exists( select 1 from sss where 名字=b.名字 and 入学日期>b.入学日期)
insert into tb values( '张三','高二','2006-01-01')
insert into tb values( '李四','高三','2003-01-02')
insert into tb values( '李四','高三','2006-08-02')
insert into tb values( '李四','高三','2004-03-03')
godelete a from tb a where 入学日期 not in (select max(入学日期) from tb where 名字 = a.名字)
select * from tbdrop table tb/*
名字 班级 入学日期
------ ------ ------------------------------------------------------
张三 高二 2006-01-01 00:00:00.000
李四 高三 2006-08-02 00:00:00.000(所影响的行数为 2 行)*/
delete a from tb a where 入学日期 not in (select max(入学日期) from tb where 名字 = a.名字)
这里的a不就是tb的别名嘛,那我不用a表示,得到的结果却只剩下一个了,也就是说他没有按名字来找到最大的时间
解释一下 谢谢~
create table tb1130(nm char(6),cls char(6),startday datetime)
insert into tb1130 values ('张三','高二','2006-01-01')
insert into tb1130 values ('李四','高三','2003-01-02')
insert into tb1130 values ('李四','高三','2006-08-02')
insert into tb1130 values ('李四','高三','2004-03-03')delete t1
from tb1130 t1
where
t1.startday<(select max(startday) from tb1130 where nm=t1.nm group by nm)select * from tb1130
警告: 聚合或其它 SET 操作消除了空值。(所影响的行数为 7604 行)