【问题标题】:Create a table with column name values available in a different table创建一个表,其中列名值在不同的表中可用
【发布时间】:2019-02-05 06:10:34
【问题描述】:

SAS Datastep - 使用不同表中可用的列名值动态创建表。

示例: 我的 Source_Table 看起来像 |字段编号|字段名称| |1|一个| |3|乙| |2| C|

/*Dynamic table creation*/
%let  s1=;
/*Column lenght should be 30 characters so I am creating a dummy variable*/
%let Dummy= 'Dummy_Dummy_Dummy_Dummy_Dummy_Dummy_Dummy';

proc sql;
    create table TEMP as 
        select 'Hi' as Work from Temp_table where 1=2
    ;
quit;

proc sort data =   Source_table
    by Field_No;
run;

proc sql;
    select Dummy||" as "||fld into :s1 seperated by "," from
    (select "&Dummy" as Dummy,substr(strip(upcase(field_name)),1,30)) as FLD 
from Source_table)
    ;
quit;

proc sql;
    create table target_table  as 
        select "&Dummy." as value_1,&s1 from TEMP where 1=2;
quit;

目标表应该是 |A|B|C|

【问题讨论】:

    标签: sas-macro datastep


    【解决方案1】:

    您的要求并不完全清楚;您特别提到使用 SAS 数据步骤,但是您的代码示例使用 PROC SQL - 使用哪个重要吗?另外,请注意您的输入有 |Field No|Field Name|1|A|3|B|2|C|但是你说输出应该按照 A-B-C 的顺序 - 字段是否应该按照 Field_No 指定的顺序?

    无论如何,这里有一些非常简单的代码:

        * Create the input data set;
        data source_table;
          field_no = 1; field_name = 'A'; output;
          field_no = 3; field_name = 'B'; output;
          field_no = 2; field_name = 'C'; output;
        run;
    
        * Derive the list of field/variable names, in the correct order;
        proc sql noprint;
          select field_name into :var_list separated by ' '
            from source_table
            order by field_no
          ;
        quit;
    
        * Create the output data set using the variable list created above;
        data target_table;
          length &var_list $ 30;
        run;
    

    如果有其他要求意味着不允许使用这种简单的方法,请更新问题以说明原因。此代码将所有指定的列创建为长度为 30 的字符变量,但可以轻松扩展以允许在 source_table 中指定每个变量的类型、长度和标签 - 这种事情一直在我的工作。

    【讨论】:

      【解决方案2】:

      谢谢你,克里斯。

      我尝试了类似的方法,并且成功了

      proc sql noprint;
      select catt(Field_name, ' char(30)') into :Col_name separated by ', '
      from Source_table
      order by field_no;
      
      create table Target_table
      (Value_1 char(30), &Col_name);
      quit;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-23
        • 2019-07-14
        • 1970-01-01
        • 2019-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多