SQL Server刪除表中的重復(fù)數(shù)據(jù)
添加示例數(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ù)多余的行,每個(gè)Name僅保留1行數(shù)據(jù)
1、查詢表中Name 重復(fù)的數(shù)據(jù)
select Name from Student group by Name having count(Name) > 1
2、有唯一列,通過唯一列最大或最小方式刪除重復(fù)記錄
檢查表中是否有主鍵或者唯一值的列,當(dāng)前可以數(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
小知識(shí)點(diǎn)
語法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
表示根據(jù)COLUMN分組,在分組內(nèi)部根據(jù) COLUMN排序,而此函數(shù)計(jì)算的值就表示每組內(nèi)部排序后的順序編號(hào)(組內(nèi)連續(xù)的唯一的)
函數(shù)“Row_Number”必須有 OVER 子句。OVER 子句必須有包含 ORDER BY
Row_Number() Over(Partition By [Name] order By [ID]) 表示已name列分組,在每組內(nèi)以ID列進(jìn)行升序排序,每組內(nèi)返回一個(gè)唯一的序號(hào)
執(zhí)行刪除腳本后查詢表數(shù)據(jù)
到此這篇關(guān)于SQL Server刪除表中重復(fù)數(shù)據(jù)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。