SQL操作應(yīng)用——?jiǎng)h除重復(fù)數(shù)據(jù)
一、具有主鍵的情況
a.具有唯一性的字段id(為唯一主鍵)
delete table
where id not in
(
select max(id) from table group by col1,col2,col3...
)
group by 子句后跟的字段就是你用來(lái)判斷重復(fù)的條件,如只有col1,
那么只要col1字段內(nèi)容相同即表示記錄相同。
b.具有聯(lián)合主鍵
假設(shè)col1+','+col2+','...col5 為聯(lián)合主鍵
select * from table where col1+','+col2+','...col5 in (
select max(col1+','+col2+','...col5) from table
where having count(*)>1
group by col1,col2,col3,col4
)
group by 子句后跟的字段就是你用來(lái)判斷重復(fù)的條件,
如只有col1,那么只要col1字段內(nèi)容相同即表示記錄相同。
c:判斷所有的字段
select * into #aa from table group by id1,id2,....
delete table
insert into table
select * from #aa
二、沒(méi)有主鍵的情況
a:用臨時(shí)表實(shí)現(xiàn)
select identity(int,1,1) as id,* into #temp from ta
delete #temp
where id not in
(
select max(id) from # group by col1,col2,col3...
)
delete table ta
inset into ta(...)
select ..... from #temp
b:用改變表結(jié)構(gòu)(加一個(gè)唯一字段)來(lái)實(shí)現(xiàn)
alter table 表 add newfield int identity(1,1)
delete 表
where newfield not in
(
select min(newfield) from 表 group by 除newfield外的所有字段
)
alter table 表 drop column newfield
·
點(diǎn)擊加載更多評(píng)論>>