SQL 查找重复记录

时间:2022-06-24 06:25:21
 
CREATE TABLE product
(
 ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
 Pid INT NOT NULL,
 Pname VARCHAR(50) NOT NULL,
 Punit CHAR(10) NOT NULL,
 Pspec VARCHAR(50),
 PbarCode VARCHAR(20),
)

INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10000,'欧莱雅日间修复','瓶','50ML','1975126589653')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10001,'欧莱雅夜间修复','瓶','50ML','1975126589643')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10002,'倩碧','盒','150ML','1545126589653')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10003,'百分百','瓶','250ML','2575126589653')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10004,'欧本洗面脸','瓶','80ML','1275126589653')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10005,'艾迪达斯','瓶','40ML','1975126589653')
INSERT INTO product(Pid,Pname,Punit,Pspec,PbarCode) VALUES(10006,'SK2','瓶','20ML','1975126589653')
 
查找:
1、--查某一列(或多列)的重复值(只能查出重复记录的值,不能整个记录的信息)
--如:查找barCode 重复的记录
select PbarCode from product
group by PbarCode
having(count(*))>1
2、--查找重复条形码商品
select * from product
where PbarCode in (
select PbarCode from product
group by PbarCode
having(count(*))>1
) order by Pid
--下面这个可以查询有多少条关键字相同的
select PbarCode,count(PbarCode) from product
group by PbarCode having count(PbarCode)>=2;
 3、--查找重复条形码商品二,跟上面的结果是一样的  by 李全
select * from product where PbarCode in
(select PbarCode from
(select p1.PbarCode,count(p1.PbarCode) number from product p1,(select distinct(PbarCode) from product) p2 where
p1.PbarCode=p2.PbarCode group by p1.PbarCode) a1 where number>1)
 转自: http://blog.csdn.net/eastlift/archive/2006/12/23/1456984.aspx