Alternative:with patient_lab_tests (patient_id,test_code,report_generated) as ( select 101,6,'Y' union all select 101,12,'Y' union all select 101,15,'N' union all select 102,6,'Y' union all select 102,12,'Y' union all select 102,15,'Y' union all select 103,6,'Y' union all select 103,12,'Y' )select count(*) as patient_count from (select patient_id from patient_lab_tests group by patient_id having avg(case when report_generated='Y' then 1 else 0 end)=1 ) as a