将 SAS 中的数据分组到特定的桶中

Grouping the data in SAS into specific buckets

我需要一些帮助来满足以下要求

当前数据集(数据集名称:SAS1):

product_no product_type status1 status2
12345      3            x       0
12345      1            x       1
123456     3            x       1
123456     6            x       0
9876       3            x+1     0
9876       1            x+1     0

所以基本上,在上面的数据集中,如果 status2=1 and status1='x' and product_type<>3,那么对于这两行,status1 应该是 'nr'。如果 status2=1 and status1='x' and product_type=3,那么对于这两行,status1 应该是 'x+1'。如果 status2=0 and status1='x+1',那么对于这两行,status1 应该是 'x+1'

所需输出(数据集名称:SAS2):

product_no product_type status1 status2
12345      3            nr      0
12345      1            nr      1
123456     3            x+1     1
123456     6            x+1     0
9876       3            x+1     0
9876       1            x+1     0

代码已尝试,但没有用:

proc sql;create table sas2 as 
select 
    a.*,
    case
    when status2=0 and status1='x+1' then 'x+1'
    WHEN status2=1 and  status1='x' and product_type=3 then 'nr'
    WHEN status2=1 and  status1='x'  and product_type ne 3 then 'x+1'
    WHEN status2=1 and  status1='NotActive' then 4
END AS status3 FROM sas1 AS a;quit;

以上代码无效。因此,例如,对于 product_no=12345,仅该特定行满足条件,而不是整个组。因此,对于 product_no=12345,应该为两行填充列 status1='nr',而不仅仅是一行。

看来您需要进行一些分组才能将计算值应用于 'two' 行。从示例数据来看,仅有的两个行组将基于 product_no。对该组的逻辑评估求和将告诉您该组中的任何行是否满足条件。 Proc SQL 查询也将在指定 group by 子句的情况下进行非聚合选择时自动重新合并。 case 语句将根据 case 语句

的第一个出现条件计算 status1

示例:

data have;input
product_no product_type status1 $ status2 ; datalines;
12345      3            x       0
12345      1            x       1
123456     3            x       1
123456     6            x       0
9876       3            x+1     0
9876       1            x+1     0
run;

proc sql;
  create table want as
  select 
    product_no
  , product_type
  , case 
      when sum(status2=1 and status1='x' and product_type ne 3) > 0 then 'nr'
      when sum(status2=1 and status1='x' and product_type eq 3) > 0 then 'x+1'
      when sum(status2=0 and status1='x+1') > 0 then 'x+1'
      else status1
    end as status1
  , status2
  from have
  group by product_no
  ;