總的思路就是先找出表中重復數據中的一條數據,插入臨時表中,刪除所有的重復數據,然后再將臨時表中的數據插入表中。所以重點是如何找出重復數據中的一條數據,有三種情況
1.重復數據完全一樣,使用distinct
select distinct * from table
2.id列不同,id類型為int,自增字段,使用聚合函數max或其他
select * from table where id in(
select MAX(id)
FROM table group by “分組字段”having COUNT(*)>1)
3.id列不同,id類型為uniqueidentifier
(1)使用row_number() over()和partition by給每一組添加行號
Select *,(row_number() Over(partition By ‘分組字段’Order BY ‘排序字段’)) RowNum From
(select * from table where ‘分組字段’in(
select ‘分組字段’ FROM table group by “分組字段”having COUNT(*)>1) t1)
(2)將行號=1的數據插入臨時表中
Select * into #A from (‘上面的sql語句’) t2 where t2.RowNum=1
注意:row_number() over()是給行加行號的
partition by用於給結果集分組,如果沒有指定那么它把整個結果集作為一個分組,參考http://blog.csdn.net/wuzhengqing1/article/details/8024634