SQL Server删除重复行是我们最常见的操作之一,下面就为您介绍六种适合不同情况的SQL Server删除重复行的方法,供您参考。
1.如果有ID字段,就是具有唯一性的字段
- delecttablewhereidnotin(
- selectmax(id)fromtablegroupbycol1,col2,col3...
- )
group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,那么只要col1字段内容相同即表示记录相同。
2. 如果是判断所有字段也可以这样
- select*into#aafromtablegroupbyid1,id2,....
- deletetable
- insertintotable
- select*from#aa
3. 没有ID的情况
- selectidentity(int,1,1)asid,*into#tempfromtabel
- delect#whereidnotin(
- selectmax(id)from#groupbycol1,col2,col3...)
- delecttable
- insetintotable(...)
- select.....from#temp
4. col1+','+col2+','...col5 联合主键
- select*fromtablewherecol1+','+col2+','...col5in(
- selectmax(col1+','+col2+','...col5)fromtable
- wherehavingcount(*)>1
- groupbycol1,col2,col3,col4
- )
group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,那么只要col1字段内容相同即表示记录相同。
5.
- selectidentity(int,1,1)asid,*into#tempfromtabel
- select*from#tempwhereidin(
- selectmax(id)from#empwherehavingcount(*)>1groupbycol1,col2,col3...)
6.
- selectdistinct*into#tempfromtablename
- deletetablename
- go
- inserttablenameselect*from#tempSqlclub
- go
- droptable#temp
以上就是SQL Server删除重复行的方法介绍