Hi all,
I am new this this site. May I know how do I do a search for duplicate items
in a column of a table only. eg If John appears twice and Jim once, in the
Name column of Student table, the Select statement should show me 2 times (
John ) ?
ThanksSee Itzik Ben-Gan's example
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Eric_Singapore" <Eric_Singapore.24lr9q@.mail.codecomments.com> wrote in
message news:Eric_Singapore.24lr9q@.mail.codecomments.com...
> Hi all,
> I am new this this site. May I know how do I do a search for duplicate
> items in a column of a table only. eg If John appears twice and Jim
> once, in the Name column of Student table, the Select statement should
> show me 2 times ( John ) ?
>
> Thanks
>
> --
> Eric_Singapore
> ---
> Posted via http://www.codecomments.com
> ---
>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment