繁体   English   中英

使用SAS的主键

[英]Primary Key using SAS

我希望SAS程序从基于速率最高的行的数据集中找到主要服务,但是当出现平局时,将第一行作为主要服务。 请参阅下面的数据集。

ID   line rate  outcome
TTT   1    .95  Primary
TTT   2    .43
RRR   1    .75  Primary
RRR   2    .75
AAA   1    .23
AAA   2    .12
AAA   3    .65  Primary

我创建了两个具有相同数据的表,然后使用以下内容

使用的代码:

proc sql;
  create table test as
  select a.ID, a.line, a.rate
    (case 
       when ((a.ID = b.ID) and (a.rate ge b.rate)) then "Primary" 
       else ' ' 
    end) as outcome
  from table1 a,table2 b
  where a.ID = b.ID;
quit;

这可能不是最佳解决方案,但我建议您分两步进行。

  1. 查找每个ID的最大值
  2. 分配主键。 使用标志变量来指示max_rate是否是第一次出现。

这是未经测试的示例代码:

    *Calculate max rate per ID;
    proc sql;
    create table temp1 as
    select a.*, max(rate) as max_rate
    from table1
    group by ID
    order by ID, line;
    quit;

    *Assign primary key;
    data want;
    set temp1;

    by ID;
    retain flag 0;

    if first.ID then flag=0;
    if rate=max_rate and flag=0 then do;
       flag=1;
       key='Primary';
     end;
     run;

    proc print data=want;
    run; 

另一个选项是带有排序的数据步骤,排序使您拥有最大的数据,最小的行位于顶部,并使用BY处理将键设置为Primary。

 proc sort data=have;
 by ID descending rate line;
 run;

 data want;
 set have;
 by id;
 if first.id then key='Primary';
 run;

 proc sort data=want;
 by id line;
 run;

proc print data=want;
run; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM