首页 > 解决方案 > 将 SAS 中的数据分组到特定的存储桶中

问题描述

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

当前数据集(数据集名称: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' 应该为两行填充,而不仅仅是一个。

标签: sasproc-sql

解决方案


看来您需要一些分组才能将计算值应用于“两”行。从样本数据中,仅有的两行组将基于product_no. 对组的逻辑评估的总和将告诉您组中的任何行是否符合标准。 当指定子句Proc SQL时进行非聚合选择时,查询也将自动重新合并。group bycase 语句将根据 case 语句status1的第一次出现 when 条件计算值

例子:

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
  ;

推荐阅读