zl程序教程

您现在的位置是:首页 >  其它

当前栏目

SqlServer2005中使用row_number()在一个查询中删除重复记录

使用 查询 一个 number 删除 row 重复记录 sqlserver2005
2023-06-13 09:14:24 时间
下面我们来看下,如何利用它来删除一个表中重复记录:
复制代码代码如下:

IfExists(Select*Fromtempdb.Information_Schema.TablesWhereTable_NameLike"#Temp%")
DropTable#temp
CreateTable#temp([Id]int,[Name]varchar(50),[Age]int,[Sex]bitdefault1)
Go
InsertInto#temp([Id],[Name],[Age],[Sex])Values(1,"James",25,default)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(1,"James",25,default)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(1,"James",25,default)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(2,"Lisa",24,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(2,"Lisa",24,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(2,"Lisa",24,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(3,"Mirsa",23,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(3,"Mirsa",23,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(3,"Mirsa",23,0)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(4,"John",26,default)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(5,"Abraham",28,default)
InsertInto#temp([Id],[Name],[Age],[Sex])Values(6,"Lincoln",30,default)
DeleteTFrom
(SelectRow_Number()Over(PartitionBy[ID],[Name],[Age],[Sex]orderBy[ID])AsRowNumber,*From#Temp)T
WhereT.RowNumber>1
Select*From#temp

注意倒数第二句脚本,我们在一个查询实现这个功能.
你可以自己执行T-SQLscript看效果.希望对您开发有帮助!