【问题标题】:Proc sql add column to order winnersProc sql将列添加到订单获胜者
【发布时间】:2018-12-10 13:07:32
【问题描述】:

我需要你的帮助,我有一个练习要求按奖牌总数排序获胜者,如果两个国家的奖牌数量相同,那么我需要按顺序比较 3 列(这是奖牌的类型) .

所以我有

sum(3columns) as total
order total desc, col1 desc , col2 desc , col3 desc

然后我将其保存为 table ,并添加 monotonic() 作为获胜者的位置 (1 2 3 4 ...) 但我有 3 个团队在 3 列中具有相同的总结果和相同的值 所以它们必须全部放置 25 个,但我正在努力做到这一点。

提前致谢

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。
  • monotonic() 不是受支持的函数,在 SQL 中可能会很棘手

标签: sql sas proc


【解决方案1】:

正确排序数据,然后使用 FIRST/LAST/BY 分组处理。

proc sort data = have;
    by descending Total_Medals descending Gold descending Silver descending Bronze;
run;

data want; 
 set have;

 by descending Total_Medals descending Gold descending Silver descending Bronze;

 Rank = _n_;
run;

【讨论】:

    【解决方案2】:

    使用first. 评估by 组中的最后一个变量来确定何时增加总体排名值。

    * sample data;
    data have (keep=eventid teamid medal);
      length eventid teamid 8 medal $8;
      do eventid = 1 to 75;
        g = ceil(100 * ranuni(123));
        do until (s ne g);
          s = ceil(100 * ranuni(123));
        end;
        do until (b ne g and b ne s);
          b = ceil(100 * ranuni(123));
        end;
    
        teamid = g; medal = 'gold'; output;
        teamid = s; medal = 'silver'; output;
        teamid = b; medal = 'bronze'; output;
      end;
    run;
    
    * compute medal count for each team;    
    proc summary noprint data=have ;
      class teamid medal;
      ways 2;
      output out=stage2(drop=_type_);
    run;
    
    * pivot categorical medal counts into wide form;
    proc transpose data=stage2 out=stage3(drop=_name_);
      by teamid;
      var _freq_;
      id medal;
    run;
    
    * compute each medaling teams total medal count;
    data stage4;
      retain teamid total gold silver bronze; * sets order of variables in pdv;
      set stage3;
      total = sum (gold, silver, bronze);
    run;
    
    * sort descendingly by total and medal quality in preparation of rank assignment;
    proc sort data=stage4;
      by descending total descending gold descending silver descending bronze;
    run;
    
    * assign dense rank;
    data want;
      set stage4;
      by descending total descending gold descending silver descending bronze;
    
      if first.bronze then /* new combination detected */
        overall_rank + 1;
    run;
    

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2020-08-15
      • 2018-05-15
      相关资源
      最近更新 更多