1. 程式人生 > >sql server 查詢去掉重複記錄

sql server 查詢去掉重複記錄

資料表結構

if exists(select * from sysobjects where name='stuInfo')
drop table stuInfo
create table stuInfo /*建立學員資訊表**/
(
 stuName varchar(20) not null,-- 姓名,非空
 stuNo char(6) not null,-- 學號,非空
 stuAge int not null,-- 年齡,int 預設為4個長度
 stuId numeric(18,0),
 stuSeat smallint ,-- 坐位
 stuAddress text -- 住址 可以為空
)
-- 給stuInfo新增一列
alter table stuInfo add id int identity(1,1) primary key;



需求:只要資料stuName 相同,則說明是兩條重複的記錄

以下為去重方法。三個方法。效率1 >2>3 推薦使用第一條

Select * from stuinfo a where not exists(select 1 from stuinfo where stuName=a.stuName and ID<a.ID)
select a.* from stuinfo a join (select min(ID)ID,stuName from stuinfo group by stuName) b on a.stuName=b.stuName and a.ID=b.ID
select * from stuinfo a where ID=(select min(ID) from stuinfo where stuName=a.stuName)

結果