I have a table like this:
+-----+-------+-----+
| id | value | ... |
+-----+-------+-----+
| 1 | A | ... |
| 1 | B | ... |
| 1 | C | ... |
| 2 | B | ... |
| 2 | C | ... |
| 3 | A | ... |
| 3 | C | ... |
| 4 | B | ... |
| 4 | A | ... |
| ... | ... | ... |
+-----+-------+-----+
I want to limit this to just ids that have both rows with A and rows with B in the value column. In this case, the table would look like this:
+-----+-------+-----+
| id | value | ... |
+-----+-------+-----+
| 1 | A | ... |
| 1 | B | ... |
| 1 | C | ... |
| 4 | B | ... |
| 4 | A | ... |
| ... | ... | ... |
+-----+-------+-----+
… because neither id 2 nor 3 had both A and B in the value column.
Is there a succinct way to locate these IDs?
select id, value
from t
where id in (
select id
from t
group by id
having bool_or(value = 'A') and bool_or(value = 'B')
)
or
select id, value
from t t0
where
exists (
select 1
from t
where id = t0.id and value = 'A'
) and
exists (
select 1
from t
where id = t0.id and value = 'B'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With