Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query group by and having all

I have a table:

Parent Child Educated
'P1', 'C1', 'YES'
'P1', 'C2', 'YES'
'P1', 'C3', 'NO'
'P2', 'C11', 'YES'
'P2', 'C12', 'NO'
'P3', 'C21', 'YES'
'P3', 'C22', 'YES'
'P4', 'C31', 'NO'
'P4', 'C32', 'NO'

Now, I need to find all the parents who have all their children educated, i.e, Educated='YES'.

Like in above case parent 'P3'

Can anyone suggest a query to fetch this

like image 556
Xavier DSouza Avatar asked Dec 24 '22 15:12

Xavier DSouza


1 Answers

I would do this as:

select parent
from t
group by parent
having max(educated) = min(educated) and max(educated) = 'YES';

The logic is slightly more complicated if educated could be NULL.

Actually, if the value is just 'YES' or 'NO', you can do the simpler:

select parent
from t
group by parent
having min(educated) = 'YES';
like image 77
Gordon Linoff Avatar answered Dec 28 '22 07:12

Gordon Linoff