如何刪除表中的重複記錄?
阿新 • • 發佈:2019-01-10
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
--測試資料
/*-----------------------------
select*fromtt
-----------------------------*/
id pid
----------------------
1 1
1 1
2 2
3 3
3 3
3 3
(所影響的行數為6行)
首先,如何查詢table中有重複記錄
select*,count(1)asrownum
fromtt
groupbyid,pid
havingcount(1)>1
id pid rownum
---------------------------------
1 1 2
3 3 3
(所影響的行數為2行)
方法一:使用distinct和臨時表
ifobject_id('tempdb..#tmp')isnotnull
droptable#tmp
selectdistinct*into#tmpfromtt
truncatetablett
insertintottselect*from#tmp
方法二:新增標識列
altertablettaddNewIDintidentity(1,1)
go
deletefromtt whereexists(select1fromttawhere a.newid>tt.newidandtt.id=a.idandtt.pid=a.pid)
go
altertablettdropcolumnNewID
go
--測試結果
/*-----------------------------
select*fromtt
-----------------------------*/
id pid
----------------------
1 1
2 2
3 3
(所影響的行數為3行)
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
--測試資料
/*-----------------------------
select*fromtt
-----------------------------*/
id pid
----------------------
1 1
1 1
2 2
3 3
3 3
3 3
(所影響的行數為6行)
首先,如何查詢table中有重複記錄
select*,count(1)asrownum
fromtt
groupbyid,pid
havingcount(1)>1
id pid rownum
---------------------------------
1 1 2
3 3 3
(所影響的行數為2行)
方法一:使用distinct和臨時表
ifobject_id('tempdb..#tmp')isnotnull
droptable#tmp
selectdistinct*into#tmpfromtt
truncatetablett
insertintottselect*from#tmp
方法二:新增標識列
altertablettaddNewIDintidentity(1,1)
go
deletefromtt whereexists(select1fromttawhere a.newid>tt.newidandtt.id=a.idandtt.pid=a.pid)
go
altertablettdropcolumnNewID
go
--測試結果
/*-----------------------------
select*fromtt
-----------------------------*/
id pid
----------------------
1 1
2 2
3 3
(所影響的行數為3行)
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>