SAS 中分组值的组合

Combination of grouped values in SAS

我试图仅在以下数据集中的记录仅因列类型不同的情况下才能找到各种组合。因此,例如:前三行仅因列类型不同

给定的数据集

ins_id    ins_number   type
1234      1234-1234-1  AU
1234      1234-1234-1  HM
1234      1234-1234-1  RE
567       567-567-12   TL
567       567-567-13   TL
9101      9101-1234-1  AU
9101      9101-1234-1  TX
9101      9101-1234-1  CN
8854      8854-1234-1  TX
8854      8854-1234-1  GB
8854      8854-1234-1  RE
8854      8854-1234-2  RX

Expected Output:
combination  count
AU,HM,RE     1
AU,TX,CN     1
TX,GB,RE     1

我尝试编写查询但没有得到所需的输出,请帮助:

proc sql;create table tst as select cp.type, 
       count(distinct ins_id)
from (select distinct fac_prod_typ from dataset3a) cp cross join
     (select distinct ins_number from dataset3a) pes left join
     dataset3a
     on dataset3a.type = cp.type and
        dataset3a.ins_number = pes.ins_number
group by cp.type, pes.ins_number;quit;

在这里使用 FIRST/LAST 逻辑很好。 要获得计数,运行 最终输出上的 PROC FREQ,这也可以让您识别混音的 ins_id。

data have;
informat ins_id . ins_number . type .;
input ins_id  $  ins_number $  type $;
cards;
1234      1234-1234-1  AU
1234      1234-1234-1  HM
1234      1234-1234-1  RE
567       567-567-12   TL
567       567-567-13   TL
9101      9101-1234-1  AU
9101      9101-1234-1  TX
9101      9101-1234-1  CN
8854      8854-1234-1  TX
8854      8854-1234-1  GB
8854      8854-1234-1  RE
;;;;

data want;
set have;
by ins_id ins_number type notsorted;
retain combo;
length combo 6.;
if first.ins_number then call missing(combo);

if first.type then combo = catx(", ", combo, type);

if last.ins_number and countw(combo)>1 then output;

run;

您需要对数据进行排序以确保类型列表在所有 ID 上保持一致。 对 SET...; BY...; 的 DOW 循环将输出每组一个类型列表。 最后一步是使用 Proc FREQ 计算每个类型列表的 ID 数量。

示例:

data have;
informat ins_id . ins_number . type .;
input ins_id  $  ins_number $  type $;
cards;
1234      1234-1234-1  AU
1234      1234-1234-1  HM
1234      1234-1234-1  RE
567       567-567-12   TL
567       567-567-13   TL
9101      9101-1234-1  AU
9101      9101-1234-1  TX
9101      9101-1234-1  CN
8854      8854-1234-1  TX
8854      8854-1234-1  GB
8854      8854-1234-1  RE
8854      8854-1234-2  RX
;

/* force specific ordering of type within group id and number */
/* necessary for proper frequency counting */
/* if sequence of types IS important do not sort and data step by ... NOTSORTED */

proc sort data=have;
  by ins_id ins_number type;
run;

data types(keep=types);
  length types 0;
  do until (last.ins_number);
    set have;
    by ins_id ins_number;
    if indexw(types, type) = 0 then types = catx(',',types,type);
  end;
  if index(types,',') then output;
run;

proc freq noprint data=types;
  table types / out=types_counts(keep=types count) ;
run;