Jonesopolis
Jonesopolis

Reputation: 25370

SQL Select Distinct

I think this is very easy, I was hoping for verification.

I have 2 columns: ID & DocumentNumber. It's a one-to-many relationship, one ID can have many document numbers.

I need to get ID's where all DocumentNumbers belonging to it are unique.

Is this what Group By is for, in conjunction with Distinct? Is it as simple as Grouping By the ID

Upvotes: 0

Views: 75

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

You can (as you're suspecting) do it using a simple GROUP BY/HAVING and using DISTINCT;

SELECT id FROM documents 
GROUP BY id
HAVING COUNT(DocumentNumber) = COUNT(DISTINCT DocumentNumber)

An SQLfiddle to test with.

Upvotes: 3

Related Questions