SQL Server中删除重复数据的2个方法
生活随笔
收集整理的這篇文章主要介紹了
SQL Server中删除重复数据的2个方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要求:
用SQL語句實現刪除一個表里面的重復數據,但要留下一條相同的數據。
思路:
需要兩條,一條是進行重復數據標示,將重復數據中隨機的一條標注為1其它的標注為0;然后還有一條語句刪除所有的標注為1的紀錄
方法一
declare @max integer,@id integerdeclare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) > 1open cur_rowsfetch cur_rows into @id,@maxwhile @@fetch_status=0beginselect @max = @max -1set rowcount @maxdelete from 表名 where 主字段 = @idfetch cur_rows into @id,@maxendclose cur_rowsset rowcount 0方法二
有兩個意義上的重復記錄,一是完全重復的記錄,也即所有字段均重復的記錄,二是部分關鍵字段重復的記錄,比如Name字段重復,而其他字段不一定重復或都重復可以忽略。
1、對于第一種重復,比較容易解決,使用
? select distinct * from tableName就可以得到無重復記錄的結果集。
如果該表需要刪除重復的記錄(重復記錄保留1條),可以按以下方法刪除
select distinct * into #Tmp from tableNamedrop table tableNameselect * into tableName from #Tmpdrop table #Tmp發生這種重復的原因是表設計不周產生的,增加唯一索引列即可解決。
2、這類重復問題通常要求保留重復記錄中的第一條記錄,操作方法如下
假設有重復的字段為Name,Address,要求得到這兩個字段唯一的結果集
select identity(int,1,1) as autoID, * into #Tmp from tableNameselect min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoIDselect * from #Tmp where autoID in(select autoID from #tmp2)最后一個select即得到了Name,Address不重復的結果集(但多了一個autoID字段,實際寫時可以寫在select子句中省去此列)
轉載于:https://www.cnblogs.com/crystal-guoguo/archive/2013/02/27/2934833.html
總結
以上是生活随笔為你收集整理的SQL Server中删除重复数据的2个方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 防火墙问题 Linux系统 /etc/s
- 下一篇: VS 2010 开发 ActiveX 开