如何用PROC SQL筛选仅含Indicator=B且无Indicator=A的唯一水果
解决方案
原代码的逻辑仅筛选出存在Indicator='b'的水果,但没有排除那些**同时存在Indicator='a'**的水果,这就是苹果、橙子被错误保留的原因。以下是几种修正后的实现方式:
方法1:使用NOT IN排除含Indicator='a'的水果
直接明确排除所有存在Indicator='a'记录的水果:
proc sql; create table unique_fruits as select distinct fruits, indicator from example where indicator='b' and fruits not in (select distinct fruits from example where indicator='a'); quit;
方法2:使用NOT EXISTS(性能更优)
当数据集较大时,NOT EXISTS的执行效率通常比NOT IN更高,逻辑是确认当前水果没有对应的Indicator='a'记录:
proc sql; create table unique_fruits as select distinct e.fruits, e.indicator from example e where e.indicator='b' and not exists (select 1 from example where fruits = e.fruits and indicator='a'); quit;
方法3:分组筛选(直接锁定仅含Indicator='b'的水果)
通过分组统计每个水果的Indicator种类,只保留仅包含'B'的水果:
proc sql; create table unique_fruits as select fruits, 'b' as indicator from example group by fruits having count(distinct indicator) = 1 and max(indicator)='b'; quit;
内容的提问来源于stack exchange,提问作者kfc123456
相关产品推荐
相关产品推荐

