方法一:去掉一列完全相同的數據(結合ID自增長字段)
1, 完全相同的數據,需要先區分出每條數據才能進一步操作。
添加自增長列以用編號區分不同的數據行。
alter table 表名 add id int identity(1,1)
-- 添加自增長列 id
2,根據編號刪除數據
delete from table a
where id in (select max(id) from table where b a.col1=b.col1 and a.col2=b.col2 )
-- 保留相關數據行中,編號最大的數據行
3, 刪除自增長列
alter table 表名 drop column id
-- 刪除臨時增加的自增長列
用一條sql語句刪除表中所相同的記錄,刪除重複數據
具有主鍵的情況 :
1.具有唯一性的字段 id(爲唯一主鍵)
delete table
where id not in
(
select max(id) from table group by col1,col2,col3...
)
group by 子句後跟的字段就是你用來判斷重複的條件,如只有col1,
那麼只要col1字段內容相同即表示記錄相同。
2.具有聯合主鍵
假設col1+','+col2+','...col5 爲聯合主鍵
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 子句後跟的字段就是你用來判斷重複的條件,
如只有col1, 那麼只要col1字段內容相同即表示記錄相同。
3.判斷所有的字段
select * into #aa from table group by id1,id2,....
delete table
insert into table
select * from #aa
方法二:去掉各列完全相同的數據
--將數據去重複後暫存到臨時表#a中
select
distinct
*
into
#a
from
table1
where
條件
delete
table1
where
刪除限制條件
--注意別誤刪
insert
into
table1
select
*
from
#a
--將暫存的數據插回數據庫
drop
table
#a
--刪除臨時表