【问题标题】:How to extract a SAS record which has the max value for a column如何提取具有列最大值的SAS记录
【发布时间】:2015-07-10 18:26:10
【问题描述】:

我有一个这样的 SAS 数据集:

col1   col2   col3   col4    col5  col6
A1     B1     C1     D1      E1    $100
A1     B1     C1     D2      E2    $200
A2     B2     C2     D3      E3    $500

前 3 列是我的关键列。我需要提取col6 的值最高的行。

所以我可以这样做:

proc sql;
   create table temp as 
   select col1,col2,col3,max(col6) as col6 
   from dataset 
   group by 1,2,3;
   select * from dataset t1 
   inner join temp t2 
   where t1.col1 = t2.col1 and t1.col2 = t2.col2 
     and t1.col3 = t2.col3 and t1.col6 = t2.col6;
quit;

但是我怎样才能通过数据传递来达到同样的效果呢?有什么办法吗?

【问题讨论】:

    标签: sql sas


    【解决方案1】:

    您的方法非常适合多种用途。如果只使用一次实际上是必不可少的,则可以使用数据步骤和哈希对象。这会读取每条记录一次,并在每次找到 col6 比尚未看到的更高的行时更新散列对象中的单行。

    data _null_;
        if 0 then set have; /*Make sure all vars used in the hash object are set up with the correct types*/
        retain highest_so_far;
        if _n_ = 1 then do;
            highest_so_far = col6;
            declare hash hi_row();
            hi_row.definekey(co1,col2,col3,col4,col5,col6);
            hi_row.definedone();
        end;
    
        set have end=eof;
    
        if col6 > highest_so_far then do;
            hi_row.clear();
            hi_row.add();
            highest_so_far = col6;
        end;
    
        if (eof) then hi_row.output(want);
    run;
    

    如果有最高的平局,这个程序将返回第一个,但可以修改它以返回任意数量的平局。

    【讨论】:

    • 错误:第 561 行第 1 列的方法参数 6 的类型不匹配。错误:预期字符类型。错误:数据步组件对象失败。在执行阶段中止。
    • 另外,我想知道这段代码(如果以某种方式工作)如何输出每个 (col1, col2, col3) 组所需的 obs。谁能解释一下?
    • 我做了一些小调整,我认为应该可以帮助您避免上述错误。
    【解决方案2】:
    数据 col;
    输入 (col1-col5)(:$2.)  col6:comma.;
        卡片;
    A1     B1     C1     D1      E1     100美元
    A1     B1     C1     D2      E2     200美元
    A2     B2     C2     D3    0      D3    0                                                                                                                                                                  = 运行;
    proc 打印
        运行
    proc 摘要 data=col;
    输出out=maxrow idgroup(max(col6)out(_all_)=);
    运行;
    proc 打印
        运行

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多