I would appreciate any help creating this query. I have tried several methods without luck. As my question is somewhat difficult for me to phrase, I will make a simple example of what I want to do. I have data that is structurally similar to the following:
ID TYPE COLOR
1 A Blue
1 B Red
1 C Green
2 C Blue
2 B Green
I want to create a query to return the types if I have an ID with two specific colors. For example I would like to find all the ID that have both Blue and Red. The query would then return:
1, A , B
The order that A and B is returned is unimportant. The data set is large, I expect many ID’s to match both conditions( maybe 50,000 or so). I should note that the type does not correlate to color thus making the problem different from this other stackoverflow question,as well as this one.
I think I need to do a subquery of some sort. But really don’t know how to proceed, Thank you.
See it on sqlfiddle.
Alternatively, if you’re happy to have the types concatenated into a delimited string, you can extract the desired data in a single pass:
See it on sqlfiddle.
Note that, if your table might contain multiple records with the same
(ID, COLOR)pair, you should replaceCOUNT(*)with the more expensiveCOUNT(DISTINCT COLOR).