sql server 怎么查询重复数据

2025-03-09 13:18:21
推荐回答(1个)
回答1:

示例,创建数据表stuinfo,有三个字段recno(自增),stuid,stuname:
CREATE TABLE [StuInfo] ([recno] [int] IDENTITY (1, 1) NOT NULL ,[stuid] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL ,[stuname] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL) ON [PRIMARY]GO

一、查某一列(或多列)的重复值。(只可以查出重复记录的值,不能查出整个记录的信息)
例如:查找stuid,stuname重复的记录:
select stuid,stuname from stuinfogroup by stuid,stunamehaving(count(*))>1

二、查某一列有重复值的记录。(此方法查出的是所有重复的记录,如果有两条记录重复的,就查出两条)
例如:查找stuid重复的记录:
select * from stuinfowhere stuid in (select stuid from stuinfogroup by stuidhaving(count(*))>1)

三、查某一列有重复值的记录。(只显示多余的记录,也就是说如果有三条记录重复的,就显示两条)
前提:需有一个不重复的列,此示例为recno。例如:查找stuid重复的记录:
select * from stuinfo s1where recno not in (select max(recno) from stuinfo s2where s1.stuid=s2.stuid