数据表中,数据是分组的,但平时录入的时候,会出现重复的一组数据,而且每组数据的条数是不定的,我怎样才能把分组相同,记录条数相同,每条记录的名称和总数都对应相同的删除,只保留录入日期是最新的那组数据!!!表中还有名称,总数相同但分组不相同的情况,数据库是ACCESS的
例: id 名称 总数 日期 组号 1 010 100 2006-10-10 cc
2 001 100 2006-10-15 aa
3 002 50 2006-10-15 aa
4 003 30 2006-10-18 bb
5 010 100 2006-10-18 cc
6 001 100 2006-10-18 aa
7 002 50 2006-10-18 aa
8 001 100 2006-10-18 bb
9 002 50 2006-10-18 bb
例: id 名称 总数 日期 组号 1 010 100 2006-10-10 cc
2 001 100 2006-10-15 aa
3 002 50 2006-10-15 aa
4 003 30 2006-10-18 bb
5 010 100 2006-10-18 cc
6 001 100 2006-10-18 aa
7 002 50 2006-10-18 aa
8 001 100 2006-10-18 bb
9 002 50 2006-10-18 bb
先建立一個相同結構的表L1
Insert Into L1(名称,总数,日期,组号)
Select A.名称,A.总数,A.日期,A.组号
From Tablename A,(Select 名称,总数,max(日期) as 日期,组号 from TableName Group By 名称,总数,组号)B
Where A.名称=B.名称 And A.总数=B.总数 And A.组号=B.组号
如果不需要考慮總數的話 可以吧條件中的“And A.总数=B.总数“去掉
Create Table Tablename
(
id int,
name varchar(10),
sumnum int,
idate smalldatetime,
groupnum char(2)
)
Insert Tablename Select '1',' 010','100','2006-10-10','cc'
Union All Select '1',' 010','100','2006-10-11','cc'
Union All Select '1',' 010','100','2006-11-10','cc'
Union All Select '1',' 010','100','2006-12-10','cc'
Union All Select '2',' 010','100','2004-12-10','aa'
Union All Select '2',' 010','100','2005-12-10','aa'
Union All Select '2',' 010','100','2006-12-10','aa'
Select Distinct A.*
From Tablename A,(Select id,name,groupnum,Max(idate) As idate From Tablename Group By id,name,groupnum) B
Where A.id=B.id And A.name=B.name And A.groupnum=B.groupnum And A.idate=B.idate
/*
測試結果
1 010 100 2006-12-10 00:00:00 cc
2 010 100 2006-12-10 00:00:00 aa
*/
Drop Table Tablename這個應該可以了吧