【问题标题】:SAS Macro - Combining multiple tables into one, controlled by another tableSAS 宏 - 将多个表合并为一个,由另一个表控制
【发布时间】:2012-06-20 10:53:33
【问题描述】:

我来晚了一个项目,想编写一个宏来规范化一些数据以导出到 SQL Server。

有两个控制表...
- 表 1 (customers) 有一个客户唯一标识符列表
- 表 2 (hierarchy) 有一个表名列表

然后有n 附加表。 (hierarchy) 中的每条记录一个(在 SourceTableName 字段中命名)。以...的形式...
- CustomerURN、Value1、Value2

我想将所有这些表合并为一个表 (sample_results),格式为...
- SourceTableName、CustomerURN、Value1、Value2

然而,应该复制的唯一记录应该是存在于 (customers) 表中的 CustomerURN。


我可以使用proc sql 以硬编码格式执行此操作,例如...

proc sql;
insert into
  SAMPLE_RESULTS
select
  'TABLE1',
  data.*
from 
  Table1    data
INNER JOIN
  customers
    ON data.CustomerURN = customers.CustomerURN

<repeat for every table>

但每周都会将新记录添加到hierarchy 表中。

有没有办法编写一个循环,从hierarchy 表中提取表名,然后调用proc sql 将数据复制到sample_results 中?

【问题讨论】:

    标签: macros sas sas-macro


    【解决方案1】:

    您可以将所有层次结构表连接在一起,然后进行一次 SQL 连接

    proc sql ;
      drop table all_hier_tables ;
    quit ;
    
        %MACRO FLAG_APPEND(DSN) ;
          /* Create new var with tablename */
          data &DSN._b ;
            length SourceTableName $32. ;
            SourceTableName = "&DSN" ;
            set &DSN ;
          run ;
    
          /* Append to master */
          proc append data=&DSN._b base=all_hier_tables force ; 
          run ;
        %MEND ;
    
        /* Append all hierarchy tables together */
        data _null_ ;
          set hierarchy ;
          code = cats('%FLAG_APPEND(' , SourceTableName , ');') ;
          call execute(code); /* run the macro */
        run ;
    
        /* Now merge in... */
        proc sql;
        insert into
          SAMPLE_RESULTS
        select
          data.*
        from 
          all_hier_tables data
        INNER JOIN
          customers
            ON data.CustomerURN = customers.CustomerURN
    quit;
    

    【讨论】:

      【解决方案2】:

      另一种方法是创建一个视图,以便它始终反映元数据表中的最新数据。调用执行函数用于从层次数据集中读取表名。这是一个示例,您应该可以对其进行修改以适合您的数据,最后一段代码与您相关。

      data class1 class2 class3;
      set sashelp.class;
      run;
      
      data hierarchy;
      input table_name $;
      cards;
      class1
      class2
      class3
      ;
      run;
      
      data ages;
      input age;
      cards;
      11
      13
      15
      ;
      run;
      
      data _null_;
      set hierarchy end=last;
      if _n_=1 then call execute('proc sql; create view sample_results_view as ' );
      if not last then call execute('select * from '||trim(table_name)||' where age in (select age from ages) union all ');
      if last then call execute('select * from '||trim(table_name)||' where age in (select age from ages); quit;');
      run;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 1970-01-01
        • 2022-01-07
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多