Extract tuples with specified common values in another column in SQL

In R, you could do

library(dplyr) 
df %>% 
   group_by(Col1) %>% 
   filter(all(vc %in% Col2))

#   Col1 Col2 
#  <int> <fct>
#1     1 ABC  
#2     1 DEF  

The Base R equivalent of that would be

df[as.logical(with(df, ave(Col2, Col1, FUN = function(x) all(vc %in% x)))), ]

#  Col1 Col2
#1    1  ABC
#4    1  DEF

We select the groups which has all of vc in them.


Here is your current query corrected:

SELECT DISTINCT t1.Col1
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.Col1 = t2.Col1
WHERE t1.Col2 = 'ABC' AND t2.Col2 = 'DEF';

Demo

The join condition is that both Col1 values are the same, the first Col2 value is ABC and the second Col2 value is DEF.

But, I would probably use the following canonical approach to this:

SELECT Col1
FROM yourTable
WHERE Col2 IN ('ABC', 'DEF')
GROUP BY Col1
HAVING MIN(Col2) <> MAX(Col2);

Tags:

Mysql

R