5

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

Xavier DSouza
  • 2,861
  • 7
  • 29
  • 40

4 Answers4

8

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';
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
5
select parent, 
       sum(case when educated='YES' then 1 else 0 end) as sum_educated,
       count(*) as count_all
from t
group by parent
having count_all=sum_educated
StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

Finding Parents that have any record with 'No' and using NOT IN to remove those from the result:

SELECT parent
FROM table
WHERE parent NOT IN (SELECT parent FROM table WHERE Educated = 'No')
GROUP BY parent
JNevill
  • 46,980
  • 4
  • 38
  • 63
  • 1
    Didn't your mum ever tell you "Do not use `IN` for lists any longer than what you'd be prepared to write by hand"? :) – Caius Jard Aug 02 '17 at 14:56
-3

select * from [YourTable] where Educated = 'Yes'

If you only want Parent column to be displayed then select Parent from [YourTable] where Educated = 'Yes'

Ace Amr
  • 108
  • 5