简体   繁体   English

SQL查询组和所有

[英]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, ie, Educated='YES'. 现在,我需要找到所有受过孩子教育的父母,即Educated ='YES'。

Like in above case parent 'P3' 像上面的情况一样父母'P3'

Can anyone suggest a query to fetch this 任何人都可以建议查询来获取此信息

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

Finding Parents that have any record with 'No' and using NOT IN to remove those from the result: 查找具有“否”的任何记录的父母并使用NOT IN从结果中删除这些记录:

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

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 . 如果educated可能是NULL那么逻辑会稍微复杂一些。

Actually, if the value is just 'YES' or 'NO' , you can do the simpler: 实际上,如果值只是'YES''NO' ,您可以更简单:

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

select * from [YourTable] where Educated = 'Yes' 从[YourTable]中选择*,其中Educated ='Yes'

If you only want Parent column to be displayed then select Parent from [YourTable] where Educated = 'Yes' 如果您只想显示父列,请从[YourTable]中选择Parent,其中Educated ='Yes'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM