建表语句
CREATE TABLE TESTDROPTABLE
(
id NVARCHAR(40) NULL,
NAME NVARCHAR(40) NULL,
firstid NVARCHAR(40) NULL,
dateinfo DATETIME NULL
)
DELETE TESTDROPTABLE
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'A','AAAA','2012-03-15')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'A','AAAA','2012-04-15')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'B','AAAA','2012-03-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'B','BBBB','2012-04-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'B','BBBB','2012-05-15')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'B','AAAA','2012-06-15')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'C','AAAA','2012-03-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'C','DDDD','2012-04-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'C','AAAA','2012-05-25')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'C','DDDD','2012-06-25')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'D','AAAA','2012-03-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'D','EEEE','2012-04-05')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'D','AAAA','2012-05-25')
INSERT INTO TESTDROPTABLE VALUES (NEWID(),'D','FFFF','2012-06-25')
==================================================================
目的是保留每个name的最新日期的那一行数据,将name其他日期的数据删除。
SQL语句:
delete from TESTDROPTABLE where dateinfo not in
(
select max(dateinfo) from TESTDROPTABLE
where name in(select name from TESTDROPTABLE group by name)
group by name
)