SQL 查询分组依据并拥有所有

SQL query group by and having all

我有一个 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'

现在,我需要找到所有 children 受过教育的 parent,即 Educated='YES'.

如上例parent'P3'

任何人都可以建议查询来获取这个

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

select * 来自 [YourTable] 其中受过教育 = 'Yes'

如果你只想显示父列 然后 select 来自 [YourTable] 的父级 其中受过教育 = 'Yes'

查找 Parents 有任何记录 'No' 并使用 NOT IN 从结果中删除那些:

SELECT parent
FROM table
WHERE parent NOT IN (SELECT parent FROM table WHERE Educated = 'No')
GROUP BY parent

我会这样做:

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

如果educated可以是NULL,逻辑会稍微复杂一些。

其实,如果值只是'YES''NO',你可以做更简单的:

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