Find rows where one column has multiple matching values in another column


I have a products table in our MS SQL Server db.

ID, productID, productname, catalogID

The business rule we are going to start using says that each catalogID can have one and only one matching productID.

One productID can have the same catalogID, but not the other way around.

Eventually we will create separate tables with foreign keys, but for now all the columns are in the same table.

How would I find those catalogIds that have more than one matching productId?

For some reason I can't get my head around this.

Thanks in advance.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
I think this will do show you the catalogs with multiple products.

SELECT tn.catalogId, COUNT(DISTINCT tn.productID) AS product_count
FROM tablename tn
GROUP BY tn.catalogid

To see the details, you can do this:
FROM tablename tn2
WHERE catalogId in (
    SELECT tn.catalogId
    FROM tablename tn
    GROUP BY tn.catalogid
    HAVING COUNT(DISTINCT tn.productID) > 1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bobinorlandoAuthor Commented:
That did the trick! Thank you!!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.