久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

SQL Server刪除表中的重復(fù)數(shù)據(jù)

瀏覽:39日期:2023-03-06 14:25:22

添加示例數(shù)據(jù)

create table Student(ID varchar(10) not null,Name varchar(10) not null,);insert into Student values("1", "zhangs");insert into Student values("2", "zhangs");insert into Student values("3", "lisi");insert into Student values("4", "lisi");insert into Student values("5", "wangwu");

刪除Name重復(fù)多余的行,每個Name僅保留1行數(shù)據(jù)

1、查詢表中Name 重復(fù)的數(shù)據(jù)

select Name from Student group by  Name having count(Name) > 1

2、有唯一列,通過唯一列最大或最小方式刪除重復(fù)記錄

檢查表中是否有主鍵或者唯一值的列,當前可以數(shù)據(jù)看到ID是唯一的,可以通過Name分組排除掉ID最大或最小的行

delete from Student  where Name in( select Name from Student group by  Name having count(Name) > 1) and  ID not in(select  max(ID) from Student group by  Name having count(Name) > 1 )

執(zhí)行刪除腳本后查詢

3、無唯一列使用ROW_NUMBER()函數(shù)刪除重復(fù)記錄

如果表中沒有唯一值的列,可以通過row_number 來刪除重復(fù)數(shù)據(jù)
重復(fù)執(zhí)行插入腳本,查看表數(shù)據(jù),表中沒有唯一列值

Delete T From (Select Row_Number() Over(Partition By [Name] order By [ID]) As RowNumber,* From Student)T Where T.RowNumber > 1

小知識點

語法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
表示根據(jù)COLUMN分組,在分組內(nèi)部根據(jù) COLUMN排序,而此函數(shù)計算的值就表示每組內(nèi)部排序后的順序編號(組內(nèi)連續(xù)的唯一的)
函數(shù)“Row_Number”必須有 OVER 子句。OVER 子句必須有包含 ORDER BY
Row_Number() Over(Partition By [Name] order By [ID]) 表示已name列分組,在每組內(nèi)以ID列進行升序排序,每組內(nèi)返回一個唯一的序號

執(zhí)行刪除腳本后查詢表數(shù)據(jù)

到此這篇關(guān)于SQL Server刪除表中重復(fù)數(shù)據(jù)的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持。

標簽: MsSQL
相關(guān)文章:
主站蜘蛛池模板: 天门市| 富川| 东方市| 廉江市| 西城区| 虞城县| 呼玛县| 华安县| 瑞安市| 罗平县| 道孚县| 衡水市| 青神县| 抚宁县| 雷州市| 亚东县| 沁源县| 那坡县| 清涧县| 虎林市| 东丰县| 莆田市| 濮阳市| 拉孜县| 麻阳| 英吉沙县| 通化市| 屯门区| 武山县| 永年县| 丘北县| 华蓥市| 高唐县| 泰兴市| 肃南| 叙永县| 繁昌县| 房山区| 丰顺县| 营口市| 温泉县|