I'm trying to solve this SQL problem, I have a dozen different colored balls and a few boxes. Now, I'm trying to write an SQL query that outputs the color of the balls that are in every box. So, if Green balls exist in Box A, B and C, but Blue and Red balls are only in 1 or 2 out of 3 boxes, I should only output Green.
I have three tables:
Box
ID |
====|
A |
B |
C |
Ball
Number | boxid | colorid |
=======|=======|=========|
1 |A | Green |
2 |A | Red |
3 |A | Blue |
4 |B | Green |
5 |B | Red |
6 |NULL | Blue |
7 |C | Green |
8 |NULL | Red |
9 |NULL | Blue |
10 |NULL | Green |
11 |NULL | Red |
12 |NULL | Blue |
NULL meaning they're not inside any of the boxes
Color
Name |
======|
Blue |
Red |
Green |
Now, at first I thought I could solve this using this code:
SELECT colorid
FROM Ball
GROUP BY colorid
HAVING COUNT(colorid) = (SELECT COUNT(*) FROM Box)
OR COUNT(colorid) > (SELECT COUNT(*) FROM Box)
But then I realized that once you give a value to the rows that have NULL on boxid it'll output those colors as well because my SQL query doesn't take into account that the colored balls have to be in all three different boxes, just that all three colored balls are in any box.
I'm stumped on how to change my query so that it only counts if the ball is in a different box than another one. Please help.