0

I'm having a bit of an issue trying to query a table. I'm trying to query all the usersid that has multiple colors. So I expect the results to be just 222 because it has red and blue values.

I have tried:

SELECT userid FROM test_table WHERE color = 'red' AND color = 'blue';  
SELECT userid FROM test_table WHERE color LIKE '%red%' AND color LIKE '%blue%'; 

I tried using or for both of these queries but they return everything.

| userid | color |
+--------+-------+
|  222   | red   |
|  222   | red   |
|  333   | red   |
|  333   | red   |
|  222   | blue  |
|  444   | blue  |
2
  • What RDBMS are you using? meta.stackoverflow.com/questions/388759/… and look into EXISTS Commented Feb 2, 2021 at 20:29
  • Apologize for not including it, I'm using MySQL Commented Feb 2, 2021 at 20:31

2 Answers 2

1

I think you can use aggregation and having:

select userid
from t
where color in ('red', 'blue')
group by userid
having count(distinct color) = 2;
Sign up to request clarification or add additional context in comments.

Comments

0

This might be a bit of overkill but this should work. The 1st Temp table was necessary to filter out duplicates where one userid had multiple of the same color. Then the second to place a row number on each userid per color entry. then just filter to only those with more than one entry. I'm assuming the end product is a unique list of userids.

DROP TABLE IF EXISTS #TempTableColor1;
Select Distinct UserID, Color
INTO #TempTableColor1
From t
where color in ('red', 'blue')

DROP TABLE IF EXISTS #TempTableColor;
Select UserID, Row_Number () Over ( Partition By USERID Order By Color) RN
INTO #TempTableColor
From #TempTableColor1
Where color in ('red', 'blue')

Select 
Distinct UserID
From #TempTableColor
Where RN > 1
Order By UserID 

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.