70

I have inserted some values in the table DataTab.

SomeId: Integer     => Autogenerated primary key.
DataId: Guid
DataNumber: Integer
DataType: varchar

The above are the column's in my tables, I want to find, if the table contains repeated DataId values. It has been a long time I had worked with databases. Now I can figure out simple queries. But I found this somewhat difficult.

I tried the following query, is this correct?

SELECT * from (Select * from DataTab) AS X 
where DataId= X.DataId AND SomeId!=X.SomeId

3 Answers 3

157
SELECT DataId, COUNT(*) c FROM DataTab GROUP BY DataId HAVING c > 1;
Sign up to request clarification or add additional context in comments.

3 Comments

And if i want to check if DataId and DataNumber both are same for a record, then the query would be as follows, SELECT DataId, COUNT(*) c FROM DataTab GROUP BY DataId,DataNumber HAVING c > 1 ,, Am i right?
SELECT DataId,DataNumber,COUNT(*) c FROM DataTab GROUP BY DataId,DataNumber HAVING c > 1. because whatever fields you'r taking in group by, it should be added in select statement.
Kindly upvote it as per stackoverflow guidelines if you found it is as per your expectation/ resolved your problem.
3

I have used it in my application. It is working based on your query

SELECT a.* 
FROM CENTERDETAILS a 
JOIN 
(SELECT IPADDR, MACID, COUNT(*) 
    FROM CENTERDETAILS  
    GROUP BY IPADDR, MACID 
    HAVING count(*) > 1
) b ON a.IPADDR = b.IPADDR OR a.MACID = b.mac 
ORDER BY a.MACID

Comments

0

I've tried to convert what I read in the OP as the original approach into something that works and is fairly easy to remember compared to the combination of GROUP BY and HAVING.

SELECT *
FROM DataTab a 
JOIN DataTab b ON
  a.DataId = b.DataId
WHERE
  a.SomeId <> b.SomeId

Although it may be less efficient than Jwalin Shah's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.