2

I have a query such as this:

select a.id, a.color, a.shade from colors a where a.color = 'red' 

which fetches

ID | Color | shade -------|------------|--------- 23 |red | dark10 525 |red | light-10 

Question:

How can I find all records in table colors where there are multiple (two) occurrences of samecolor AND their corresponding shades are NOT identical

e.g. records like the following will not be considered

ID | Color | shade -------|------------|--------- 23 |green | light-10 324 |green | light-10 

1 Answer 1

3

You can do this by utilizing a GROUP BY clause with a HAVING COUNT(*) = 1 condition:

declare @colors table ( id int, color nvarchar(100), shade nvarchar(100) ) insert into @colors select 23, 'red', 'dark10' union all select 525, 'red', 'light-10' union all select 23, 'green', 'light-10' union all select 324, 'green', 'light-10' select c.* from @colors c inner join ( select color, shade from @colors group by color, shade having COUNT(*) > 1 ) x on x.color = c.color and x.shade <> c.shade 
Sign up to request clarification or add additional context in comments.

2 Comments

I've corrected your answer relative to the question. I'll accept your answer. thanks
Thanks - I didn't have a ton of data to test on, so I appreciate you updating it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.