如何用Proc SQL分组仅含特定成员类型的住户记录?
仅筛选特定人群住户的Proc SQL解决方案
核心逻辑
要筛选全部成员都属于目标人群且满足人数要求的住户,核心是确保分组后:
- 住户内无不符合条件的成员
- 成员数量匹配需求
针对非数值型性别字段的实现
假设你的gender字段是字符型(例如'F'代表女性,'M'代表男性),要筛选仅2位女性居住的住户,可使用以下代码:
proc sql; create table only_female_hh as select household, count(*) as member_count from table group by household /* 确保所有成员都是女性:最小和最大gender值都是'F' */ having min(gender) = 'F' and max(gender) = 'F' /* 限定住户成员数为2 */ and count(*) = 2; quit;
如果gender是数值型(例如1代表女性,2代表男性),只需把判断值换成对应数值即可:
proc sql; create table only_female_hh as select household, count(*) as member_count from table group by household having min(gender) = 1 and max(gender) = 1 and count(*) = 2; quit;
通用适配写法(更直观)
不管字段是字符还是数值,都可以用CASE统计不符合条件的成员数,要求其为0,逻辑更清晰:
proc sql; create table only_female_hh as select household, count(*) as member_count from table group by household /* 统计非女性成员数,要求为0 */ having sum(case when gender ne 'F' then 1 else 0 end) = 0 and count(*) = 2; quit;
这种写法也能轻松适配其他筛选场景,比如你之前的20岁以下人群筛选,可修改为:
proc sql; create table under20_hh as select household, count(*) as freq from table group by household having sum(case when age >= 21 then 1 else 0 end) = 0; quit;
内容的提问来源于stack exchange,提问作者Kristián Övári
相关产品推荐
相关产品推荐

